我需要在HTTP响应中发送一个CSV文件。如何将输出响应设置为CSV格式?

这是行不通的:

Response.ContentType = "application/CSV";

当前回答

我发现IE的问题是,它嗅探返回数据,并对它认为已经发送的内容类型做出自己的判断。这导致了许多副作用,例如总是打开文本文件的saveAs对话框,因为您正在使用数据传输的压缩。解决方案是(在php代码中)......

header('X-Content-Type-Options: nosniff');

其他回答

就像这样使用

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");
Response.Write(t.ToString());
Response.End();

试试其他的mime类型(从这里:http://filext.com/file-extension/CSV)

文本/逗号分隔值 文本/ csv 应用程序/ csv 应用程序/ excel 应用程序/ vnd.ms-excel 应用程序/ vnd.msexcel

此外,mime类型可能是区分大小写的……

使用text/csv作为内容类型。

我建议在'myfilename.cvs'前面插入一个'/'字符

Response.AddHeader("Content-Disposition", "attachment;filename=/myfilename.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.