【问题标题】:Export csv file with encoding in MVC controller在 MVC 控制器中使用编码导出 csv 文件
【发布时间】:2016-12-16 17:18:36
【问题描述】:

我有以下用于导出 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[]。

【问题讨论】:

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


    【解决方案1】:

    基于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);
                }
    

    这就成功了。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
         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.
        

        【讨论】:

        • 你的意思是我必须将它附加到我的数据字符串中吗?
        猜你喜欢
        • 1970-01-01
        • 2017-01-22
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多