很多时候,都要把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进行编码,对流也可进行相应编码