您的位置:首页 > 编程语言 > C#

导出Excel文档 解决导出Excel文档显示乱码 在C#桌面程序导出Excel文档

2008-04-10 03:15 435 查看
//以下代码在Win程序运行功能成功,注意的一点是在Win程序中用了ASP.NET的WEB控件DataGrid1

//代码亦可在WEB中运行

//绑定数据到DataGrid1
this.DataGrid1.DataSource = SourceTb.DefaultView;
this.DataGrid1.DataBind();

//将DataGrid1构成的html代码写进StringWriter +
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw);
string HtmlInfo = tw.ToString().Trim();
//此句可解决导出的Excel文档显示乱码"<meta http-equiv=Content-Type content=text/html;charset=gb2312>"
HtmlInfo="<meta http-equiv=Content-Type content=text/html;charset=gb2312>"+HtmlInfo;
//MessageBox.Show(HtmlInfo,"提示");
//得到Excel文件的物理地址
string FilePathName = "要保存文档的路径//文档名.xls";
System.IO.File.Delete(FilePathName);
FileStream Fs = new FileStream(FilePathName, FileMode.Create);
BinaryWriter BWriter= new BinaryWriter(Fs,System.Text.Encoding.GetEncoding("GB18030"));
//将DataGrid的信息写入Excel文件
BWriter.Write(HtmlInfo);
BWriter.Close();
Fs.Close();

如果没什么特别的要求,第一种可以满足基本导出文档,并不会显示乱码的要求.

其它在WEB上的写法:

一般常用的方法为:
DataGrid1.DataSource = this.GetDataSource();
DataGrid1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw );
Response.Write(tw.ToString());
Response.End();

但是有时导出会出现乱码,有时则不会出现乱码.真是百思不得其解.

我们可以这样解决将
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
换成:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition","attachment;filename=/"" + HttpUtility.UrlEncode("全部销售记录["+DateTime.Now.ToString("yyyy-MM-dd")+"]",System.Text.Encoding.UTF8) + ".xls/"");

为什么直接输出到Excel会出现乱码,而用Excel打开这段Html不会出现乱码呢?暂时能解决问题但还是不明白,希望高手能给予释疑!

还有这一写法,该写法与第一种类似,但以下写法与第二种写法一样,有时会有乱码,有时不会.

//绑定数据到DataGrid1
this.DataGrid1.DataSource = SourceTb.DefaultView;
this.DataGrid1.DataBind();
//将DataGrid1构成的html代码写进StringWriter
this.DataGrid1.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
this.DataGrid1.RenderControl(hw);
string HtmlInfo = tw.ToString().Trim();

string DocFileName = "审批信息.xls";
string FilePathName = Request.PhysicalPath;
FilePathName = FilePathName.Substring(0,FilePathName.LastIndexOf("//"));
//得到Excel文件的物理地址
FilePathName = FilePathName +"//" + DocFileName;
System.IO.File.Delete(FilePathName);
FileStream Fs = new FileStream(FilePathName, FileMode.Create);
BinaryWriter BWriter= new BinaryWriter(Fs,System.Text.Encoding.GetEncoding("GB18030"));
//将DataGrid的信息写入Excel文件
BWriter.Write(HtmlInfo);
BWriter.Close();
Fs.Close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: