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

这是行不通的:

Response.ContentType = "application/CSV";

当前回答

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

其他回答

根据RFC 4180, CSV的MIME类型为text/ CSV。

就像这样使用

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

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

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

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

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

对于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.