求一段代码:
1 把DataTable的内容导出到excel中!
2 用户点击一个按钮,给用户下载这个excel文件

解决方案 »

  1.   

    http://edu.hn8868.com/Article/ASP/ASP/200506/9694.html
    把网页另存为txt文件就可以了
      

  2.   

    我这里有一个,这是我刚用打VB.NET转为C#写的。excel文件保存在服务中。
    private void TransferExcel()
    {
    Excel.Application oExcel= new Excel.ApplicationClass();
    Excel.Workbook oBook ;
    Excel.Workbooks oBooks;
    Excel.Worksheet oSheet;
    Excel.Sheets oSheets;
    Excel.Range oCells;
    string sFile,sTemplate;
    object Nothing = System.Reflection.Missing.Value;
      //定义一个datatable
    DataTable objDataTable = new DataTable();
    //把DataGrid中的数据导入datatable中
    objDataTable = (DataTable)Session["objDataTable"];
    sFile = Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyExcel"+Request.Cookies["StaffID"].Value.ToString()+".xls";
    //定义模版文件
    sTemplate = Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyTemplate.xls";
    oExcel.Visible = false;
      oExcel.DisplayAlerts = false;

    //定义一个新的工作簿
      oBooks = oExcel.Workbooks;
      oBooks.Open(Server.MapPath(Request.ApplicationPath) + "\\Excel\\MyTemplate.xls",Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);
    oBook = oBooks[1];
      oSheets = oBook.Worksheets;
      oSheet = (Excel.Worksheet)oSheets[1];
    //命名该sheet
      oSheet.Name = "工资表";
      oCells = oSheet.Cells;
      //调用dumpdata过程,将数据导入到Excel中去
      DumpData(objDataTable, oCells);
      //保存
      oSheet.SaveAs(sFile,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);
    oBook.Close(false,Nothing,Nothing);  //退出Excel,并且释放调用的COM资源;
    oExcel.Quit();
      Marshal.ReleaseComObject(oCells);
    Marshal.ReleaseComObject(oSheet);
      Marshal.ReleaseComObject(oSheets);
    Marshal.ReleaseComObject(oBook);
      Marshal.ReleaseComObject(oBooks);
    Marshal.ReleaseComObject(oExcel);
      oExcel = null;
    oBooks = null;
    oBook = null;
      oSheets = null;
    oSheet = null;
    oCells = null;
      System.GC.Collect();
      Response.Redirect(sFile);
    }
    private void DumpData(DataTable dt,Excel.Range oCells)
    {
    int i,iCol,iRow;
    //输出列标题
    for(iCol=0;iCol < dt.Columns.Count;iCol++)
    {
    oCells[1,iCol+1] = dt.Columns[iCol].ToString();
    }
    //Response.Write("\n");
    //将数据导出到相应的单元格
    for(iRow=0;iRow <dt.Rows.Count;iRow++)
    {
    for(i=0;i<dt.Columns.Count;i++)
    {
    oCells[iRow+2,i+1] = dt.Rows[iRow].ItemArray[i].ToString();
    Response.Write(dt.Rows[iRow].ItemArray[i].ToString()+"\t");
    }
    }
    }
      

  3.   

    需要添加<identity impersonate="true"/>到web.config中。在本文中,要给予WEB目录可写的权限。
    由于我们要使用的是Excel,所以添加一个关于COM的应用,这里添加的是Microsoft Excel Object Library。
    在代码上面加入:
    using System.Runtime.InteropServices;
    using Microsoft.Office;
    我现在用的很正常!
      

  4.   

    运行这段代码,在客户端就显示那保存的Excel文件!以Excel文件打开,那里就可以保存到客户端或打印了