请教关于使用StreamReader导出EXCEL乱码问题?
我要开发在WEB上使用EXCEL的报表功能,通过在网上查找发现了几种方法,但要么灵活性不够,要么太复杂(纯个人意见),所以借鉴一下网上的方法来实现了
首先是制作好模版,先把需要导出的EXCEL报表制作好设置列的格式表头和标题等等
然后另存为网页,这时候EXCEL就可以直接用文本打开,发现变成了一可以修改的网页,
在网页里可以看到在需要填充数据的位置上有 <![if supportMisalignedColumns]>
这个自动生成的注释(没有或不一样可以自行添加设定),刚好可以利用为填充数据的标签
最后手动修改后缀名.xls,这样模版搞好了
下一步后台代码实现
System.Web.UI.WebControls.DataGrid dgExport = null;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
DataSet mydst=null;
string strTmpSql,strSql,strTmp;
StringBuilder strLine=new StringBuilder();
//设置编码和附件格式
//System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("司机人员资料", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312";
//为装载DataGrid里的HTML准备
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
//开始填充需要的数据在DataGrid中
strSql=(string)ViewState["visSql"];//我使用ViewState来装载全局使用SQL语句
strTmpSql=" CarID as 自编号,CarType as 车型,BuyType as 营运模式,CarNo as 车牌号,DriverName as 司机姓 +"名,LicenseNo as 资格证号,DriverEnterCarTime as 签入时间 ";
strSql=strSql.Replace("*",strTmpSql) + " order by CarID ,CarMaster ";
//填充
dgExport = new System.Web.UI.WebControls.DataGrid();
mydst=DbHelperSQL.Query(strSql);//自己写的类返回DataSet
dgExport.DataSource = mydst.Tables[0].DefaultView;
dgExport.AllowPaging = false;
dgExport.ShowHeader=false;
dgExport.DataBind();
//读取模版EXCEL
System.IO.StreamReader strHtmlToExcel =new StreamReader(Server.MapPath("~") + "\\ExcelRpt\\" + "司机资料信息列表.xls",System.Text.Encoding.GetEncoding("gb2312"),false);//System.Text.Encoding.GetEncoding("gb2312")这里我曾经试过其他也是乱码
//读取,以标签为截止位
for(strTmp=strHtmlToExcel.ReadLine();strTmp!=" <![if supportMisalignedColumns]>";strTmp=strHtmlToExcel.ReadLine())
{
strLine.Append(strTmp);
strTmp="";
}
//装载需要填充的数据
dgExport.RenderControl(htmlWriter);
strLine.Append(strWriter.ToString());
strLine.Append(strHtmlToExcel.ReadToEnd());
curContext.Response.Write(strLine.ToString());
curContext.Response.End();
经过调试效果还可以灵活性强,复杂度不高,
但问题来了~!当我打开报表时是乱码,中文显示不了啊!!请问各位大大究竟哪里搞错啊?应该怎样才不会乱码啊?
补充说明:当我不使用读取模版这种用法时是不会乱码的~!