ASP.NET 将DataTable导入到Excel

今天在弄页面上的打印功能,就是把Gridview里的数据打印出来。首先就是将Gridv里的数据导入到Excel,再打印,很简单。然而,到网上找了很多资料,就是不行。

有好几个错误,记得最清楚的是Clsid{……}错误。按照网友说的,做了也不行。

竟然把代码拷到同事的机器上,就行了。啥原因?同事的机上安装的是101M的office 2003。我的机子上的Office是绿化版。我也安了那个101M的office 2003,结果就行了。

操作过程:
添加引用.NET下Microsoft.Office.Interop.Excel      11.0.0.0     v1.1.4322
到项目中,Bin下会有Microsoft.Office.Interop.Excel.dll

打印类

Code


后面那段Response 是让excel以下载的形式打开。

PS:html方式导出Excel

HTML方式导出Excel
Response.Clear();
Response.Buffer
= true;

Response.Charset
= "utf-8";

//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开

//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm  

Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename) + ".xls");

Response.ContentEncoding
= System.Text.Encoding.GetEncoding("utf-8");

//Response.ContentType指定文件类型 可以为application/ms-excel    application/ms-word    application/ms-txt    application/ms-html    或其他浏览器可直接支持文档 

Response.ContentType
= "application/ms-excel";

this.EnableViewState = false;


System.IO.StringWriter oStringWriter
= new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter
= new System.Web.UI.HtmlTextWriter(oStringWriter);

this.RenderControl(oHtmlTextWriter);
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件  

Response.Write(oStringWriter.ToString());

Response.End();
原文地址:https://www.cnblogs.com/lhking/p/1455136.html