在MVC控制器中导出带有编码的csv文件

时间:2016-08-10 10:55:56

标签: c# asp.net-mvc csv character-encoding

我有以下用于导出csv文件的控制器操作

public ActionResult ExportExcel(int projectId)
        {
            var risks = new RiskRepository().GetRisksByProjectId(projectId);
            var commaDelimmeted =
                    risks.Select(
                        r => r.RiskDescription + "," + r.RiskTypeId.ToString() + "," + r.Likelihood.ToString() + "," + r.Impact + "," + r.Action + "," + r.ActionBy + ",")
                        .ToList();

            string data = commaDelimmeted.Aggregate(string.Empty, (current, line) => current + line + Environment.NewLine);

            Response.ClearContent();
            Response.Buffer = true;
            // set the header
            var aliasName = "someFile.csv";
            Response.AddHeader("content-disposition", "attachment; filename=" + aliasName);
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.ContentEncoding = Encoding.UTF8;
            Response.Output.Write(data);
            Response.Flush();
            Response.End();

            return File(Response.OutputStream, "application/csv");
        }

输出csv文件没有正确显示从右到左的语言字符,因此我设置了响应内容编码标题,问题仍然存在。

有什么想法吗?

编辑:在this帖子中查看Darin的解决方案并没有解决我的问题,输出显示了csv输出文件中的System.Byte []。

3 个答案:

答案 0 :(得分:0)

 Have you tried setting the encoding in a meta tag in the HTML?

 <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
   Excel won't see the response headers, so it won't know what the Response.Encoding is. The meta tag allows it to find out.

答案 1 :(得分:0)

除非您绝对需要将其作为CSV文件,否则我建议将其转换为使用ClosedML(在NuGet上可用)生成正确的XLSX文件 - 然后您可以使用GetMimeMapping函数并返回FileStreamResult。

答案 2 :(得分:0)

基于this post,结果是编码前导码必须附加到csv数据,如下所示:

using (var sw = System.IO.File.Create(csvPath))
            {
                var preamble = Encoding.UTF8.GetPreamble();
                sw.Write(preamble, 0, preamble.Length);
                var databytes = Encoding.UTF8.GetBytes(data);
                sw.Write(databytes, 0, data.Length);
            }

这就是诀窍。