我需要在HTTP响应中发送一个CSV文件。如何将输出响应设置为CSV格式?
这是行不通的:
Response.ContentType = "application/CSV";
我需要在HTTP响应中发送一个CSV文件。如何将输出响应设置为CSV格式?
这是行不通的:
Response.ContentType = "application/CSV";
当前回答
对于c# MVC 4.5,你需要这样做:
Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".csv\"");
Response.Write(dataNeedToPrint);
Response.End();
return new EmptyResult(); //this line is important else it will not work.
其他回答
如上所述设置内容类型和内容配置会在不同的浏览器中产生截然不同的结果:
IE8:按需要保存对话框,Excel为默认应用程序。100%好。
Firefox:保存对话框确实显示,但Firefox不知道它是一个电子表格。建议用Visual Studio打开它!50%的好
Chrome:提示完全被忽略。CSV数据显示在浏览器中。0%的好。
当然,在所有这些情况下,我指的是浏览器,因为它们没有自定义的mime/应用程序映射。
就像这样使用
Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");
Response.Write(t.ToString());
Response.End();
我建议在'myfilename.cvs'前面插入一个'/'字符
Response.AddHeader("Content-Disposition", "attachment;filename=/myfilename.csv");
我希望你能取得更好的成绩。
根据RFC 4180, CSV的MIME类型为text/ CSV。
对于c# MVC 4.5,你需要这样做:
Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".csv\"");
Response.Write(dataNeedToPrint);
Response.End();
return new EmptyResult(); //this line is important else it will not work.