我需要在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.
其他回答
使用text/csv作为内容类型。
根据RFC 4180, CSV的MIME类型为text/ CSV。
我发现IE的问题是,它嗅探返回数据,并对它认为已经发送的内容类型做出自己的判断。这导致了许多副作用,例如总是打开文本文件的saveAs对话框,因为您正在使用数据传输的压缩。解决方案是(在php代码中)......
header('X-Content-Type-Options: nosniff');
对于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.
就像这样使用
Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");
Response.Write(t.ToString());
Response.End();