ASP.NET Excel 导出编码问题

编程入门 行业动态 更新时间:2024-10-28 07:32:10
本文介绍了ASP.NET Excel 导出编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 ASP.NET 站点上进行一些 Excel 导出.除了编码之外,一切正常.当我在 Excel 中打开它时,它看起来像这样:

I'm doing some Excel Exports on the ASP.NET Site. Everything works except of the Encoding. When I open it in Excel, it looks like this:

Eingabe Kosten je Gerät Gerät:Gerätebezeichnung:Betriebsmittel Heizöl 在 €:4Dieselverbrauch 在 €:4

Eingabe Kosten je Gerät Gerät: Gerätebezeichnung: Betriebsmittel Heizöl in €: 4 Dieselverbrauch in €: 4

这是我的代码:

Response.Clear();
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename=NachkalkGeraete.xls;");
var writer = new HtmlTextWriter(Response.Output);

SomeControl.RenderControl(writer); /* FormView, Table, DataGrid... */

Response.End();

我已经尝试明确设置编码..但没有发生任何变化:

I've already tried explicitly set the Encoding.. but no change occured:

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=NachkalkGeraete.xls");

Response.BufferOutput = true;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "UTF-8";
EnableViewState = false;

System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);

SomeControl.RenderControl(hw);

Response.Write(tw.ToString());
Response.End();

请问怎么了?

推荐答案

好吧,我发现问题可能出在 excel 文件的标题中,它不包含 BOM 字节序列(在代表使用的编码的文件的开头).

Well I found out that the problem could be in the header of the excel file, that it does not contain the BOM byte sequence (at the beginning of the file representing the encoding used).

所以我是这样做的,它对我有用:

So I made it this way and it works for me:

Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=Test.xls");   
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

FormView1.RenderControl(hw);

Response.Write(sw.ToString());
Response.End(); 

这篇关于ASP.NET Excel 导出编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-31 02:10:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/793573.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ASP   NET   Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!