[英]Export csv file with encoding in MVC controller
我有以下用於導出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文件無法正確顯示從右到左的語言字符,因此我將響應內容編碼標頭設置為問題仍然存在。
有什么想法嗎?
編輯:看這篇文章中達林的解決方案不能解決我的問題,在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。
根據這篇文章 ,事實證明編碼前導必須附加到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);
}
這成功了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.