您的位置:首页 > 其它

文件流形式导出为Excel的文件编码问题

2005-06-27 17:06 381 查看
今天作项目的时候遇到一个问题:
DataGrid内容导出为Excel文件有可能乱码。

描述如下:
简体中文系统中web.config文件设置了<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-cn" />

系统里面有a.aspx提供了一个Datagrid,和Button,点击Button的时候将Datagrid的内容导出为Excel。当a.aspx被不同页面调用的时候导出的excel文件有可能会乱码,但又不是全部情况都乱码。调试了半天也没有发现问题。

1string filename = "" ;
2 filename = DateTime.Now.ToString("yyyy-MM-dd") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
3 Response.Clear();
4 Response.Buffer= true;
5 Response.AppendHeader("Content-Disposition","attachment;filename=" + filename + ".xls");
6 Response.ContentType = "application/ms-excel";
7 this.EnableViewState = false;
8 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-cn",true);
9 System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
10 System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
11 DataGrid_BudgetUsedList.RenderControl(oHtmlTextWriter);
12 Response.Write(oStringWriter.ToString());
13 Response.End();
14
最后发现是编码问题

1string filename = "" ;
2 filename = DateTime.Now.ToString("yyyy-MM-dd") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
3 Response.Clear();
4 Response.Buffer= true;
5 Response.AppendHeader("Content-Disposition","attachment;filename=" + filename + ".xls");
6 Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8"); //更改为Utf-8编码后正常
7 Response.ContentType = "application/ms-excel";
8 this.EnableViewState = false;
9 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-cn",true);
10 System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
11 System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
12 DataGrid_BudgetUsedList.RenderControl(oHtmlTextWriter);
13 Response.Write(oStringWriter.ToString());
14 Response.End();
15
设置ContentEncoding为UTF-8之后显示正常。
唉~受习惯思维影响,习惯性认为简体中文系统就应该是gb2312。有时候换一下思维问题也就解决了。

ps:系统使用Utf-8编码应该是最佳方案,但是有时候受一些东西的影响也只能使用GB2312了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: