I need to send a CSV file in HTTP response. How can I set the output response as CSV format?
This is not working:
Response.ContentType = "application/CSV";
-
text/csv, according to http://en.wikipedia.org/wiki/Comma-separated_values
Biswanath : Right, you should use text in place of application. -
Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )
- text/comma-separated-values
- text/csv
- application/csv
- application/excel
- application/vnd.ms-excel
- application/vnd.msexcel
Also, the mime-type might be case sensitive...
-
Using
text/csv
is the most appropriate type.You should also consider adding a
Content-Disposition
header to the response. Often a text/csv will be loaded by a Internet Explorer directly into a hosted instance of Excel. This may or may not be a desirable result.Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
The above will cause a file "Save as" dialog to appear which may be what you intend.
matt b : Firefox 3.0.10 seems to require that the value of the header be in the reverse order: attachment; filename=myfilename.csvKrzysztof Sikorski : According to RFC#2183 first is the type (attachment) and after it the parameters (filename etc)Matt Sheppard : Corrected ordering in header value. -
MIME type of the CSV is text/csv according to RFC 4180.
-
Setting the content type and the content disposition as described above produces wildly varying results with different browsers:
IE8: SaveAs dialog as desired, and Excel as the default app. 100% good.
Firefox: SaveAs dialog does show up, but Firefox has no idea it is a spreadsheet. Suggests opening it with Visual Studio! 50% good
Chrome: the hints are fully ignored. The CSV data is shown in the browser. 0% good.
Of course in all of these cases I'm referring to the browsers as they come out of they box, with no customization of the mime/application mappings.
Martin : If Firefox wants you to open with Visual Studio, means you are exporting the HTML and not a CSV. -
Just Use like that
Response.Clear(); Response.ContentType = "application/CSV"; Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\""); Response.Write(t.ToString()); Response.End();
Chris : Don't forget response.clear() first. -
Over the years I've been honing a perfect set of headers for this that work brilliantly in all browsers that I know of
// these headers avoid IE problems when using https: // see http://support.microsoft.com/kb/812935 header("Cache-Control: must-revalidate"); header("Pragma: must-revalidate"); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: attachment; filename=$filename.csv");
0 comments:
Post a Comment