要解决中文乱码问题,首先我们需要知道原因,一开始我尝试了gb2312,utf-8等多种编码格式导出,使用 Execl 打开均为乱码,后来无意中发现,必须为“带 BOM 的 UTF-8”。
代码示例:
using(var sw = new File.CreateText(fileName))
{
sw .WriteLine(csvContent);
}
如果是asp.net页面输出,则为:
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToShortDateString() + fileName + ".xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "utf-8";
Response.ContentType = "text/csv";
using(var outputWriter = new StreamWriter(Response.OutputStream, System.Text.Encoding.UTF8))
{
outputWriter.WriteLine(csvContent);
}
Response.Flush();
Response.End();