测试通过的c#导出Excel

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testSaveTxt.aspx.cs" Inherits="test_testSaveTxt" %>
<script type="text/javascript">

 function AllAreaExcel(export1)
      {
   var curTbl = document.getElementById(export1);
       var oXL = new ActiveXObject("Excel.Application");
       var oWB = oXL.Workbooks.Add();
       var oSheet = oWB.ActiveSheet;
       var sel=document.body.createTextRange();
       sel.moveToElementText(curTbl);
       sel.select();
       sel.execCommand("Copy");
       oSheet.Paste();
       oXL.Visible = true;
      }
   AllAreaExcel('excelDoc');
</script>

 

 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Database;

public partial class test_testSaveTxt : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    ConnDbForSqlServer cd = new ConnDbForSqlServer();
  DataSet cdds=cd.ReturnDs2("select top 100 * from shop");
  DataTable table = cdds.Tables[0];
  ArrayList Cols=new ArrayList();
  foreach (DataColumn col in table.Columns)  { Cols.Add(col.ColumnName.ToString()); }


  Response.Write("<div id='excelDoc' name='excelDoc' style=/"MARGIN-TOP: 0px/" >");
  if(Cols.Count!=0){
   Response.Write("<table border=1 >");
   Response.Write("<tr>");
   foreach(object obj in Cols){
   Response.Write("<th>"+obj.ToString()+"</th>");
   }
   Response.Write("</tr>");
            foreach (DataRow Rs in table.Rows)
            {
    Response.Write("<tr>");
    foreach(object obj in Cols){
    Response.Write("<td>"+ Rs[obj.ToString()].ToString() +"</td>");
    }  
    Response.Write("</tr>");
            }

       Response.Write("</table></div>");
  }

    }
}

你可能感兴趣的:(测试通过的c#导出Excel)