简体   繁体   English

在MVC控制器中导出具有编码的CSV文件

[英]Export csv file with encoding in MVC controller

I have the following controller action used to export a csv file 我有以下用于导出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");
        }

The output csv file do not show right to left langauge characters properly, so I've set response content encoding header the problem still exists. 输出的csv文件无法正确显示从右到左的语言字符,因此我将响应内容编码标头设置为问题仍然存在。

Any thoughts? 有什么想法吗?

Edit : Looking at Darin's solution in this post didn't fix my problem , the output shows System.Byte[] in the csv output file. 编辑:看这篇文章中达林的解决方案不能解决我的问题,在csv输出文件中输出显示System.Byte []。

 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.

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

Based on this post , it turns out the encoding preamble must be appended to the csv data like this : 根据这篇文章 ,事实证明编码前导必须附加到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);
            }

and this did the trick. 这成功了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM