导出到Excel和Word

很多时候,都要把Asp.net网页导出到Excel或者Word里,尤其是DataGrid内容的导出。总的说来,有两种主要的方法。一种是在客户端用JScript或者VBScript操作ExcelApplication或者WordApplication对象,用类似VBA的方式操作Excel或者Word。还有一种是在服务器用C#或者VB.NET操作VBA对象,这跟客户端很类似,但这种方案因为大量消耗服务器资源而很少采用,一般用HTTP的Header,在header里设置几个关键字让IE知道这是什么类型,从而正确打开。下面详细说明:

方案一:用ContentType = "application/octet-stream", "Content-Disposition" = "attachment;filename = ... ",表示这是一个要下载的文件,然后将文件流输出到Response里

Response.ContentType = "application/octet-stream"
Response.AppendHeader("Content-Disposition", "attachment;filename = " & HttpUtility.UrlEncode("bill.doc", System.Text.Encoding.Default))
Response.WriteFile(bill.doc)

方案二:用ContentType = "application/msword", "Content-Disposition" = "attachment;filename = ... "

HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.txt");
   HttpContext.Current.Response.Charset = "gb2312";    
   HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; 
   HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
  // HttpContext.Current.Response.ContentType ="application/Microsoft Excel";
  // ctl.Page.EnableViewState = false;
   System.IO.StringWriter tw = new System.IO.StringWriter();
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
   ctl.RenderControl(hw);
   HttpContext.Current.Response.Write(tw.ToString());
   HttpContext.Current.Response.End();
   ctl.Visible = false;

上述两种方案可能遇到的问题:中文乱码。解决办法就是设置web.config里的global编码和导出的Excel和Word的编码一致,可多试一下Encoding.Default和Encoding.Utf8两种编码,对文件的url,可用HttpUtility.UrlEncode进行编码,对流也可进行相应编码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值