David Dubinski
David Dubinski

Reputation: 13

Generating proper CSV files

I'm having a problem programmatically generating a proper CSV file that is then downloaded by the user and opened in excel in my ASP.NET project. Excel seems to open the file properly but when I go to “save as” it defaults to Unicode text. I understand that CSV is basically a text file but if you try creating a CSV in Excel, saving, and then going to save as it will default the save as type to CSV. Therefore I believe something extra is being saved along with the file. I’ve made sure the HTTP header context-type is set to “text/csv” so I am sure that the response is correct to the user.

Upvotes: 1

Views: 303

Answers (3)

Cory Nelson
Cory Nelson

Reputation: 29981

We generate a lot of CSV where I work, and I've noticed this a lot. There's a really good chance that your file is just fine.

The problem with CSV is that it's not defined by any standard, so every app interprets it slightly different. Excel probably does this for any CSV file which isn't precisely in its preferred format.

Maybe Excel expects CSV to be ASCII, and you've got a UTF BOM in the file which makes it decide tab-delimited "Unicode text" is a better fit.

Upvotes: 2

Alex Filipovici
Alex Filipovici

Reputation: 32561

This should work:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
    Response.ContentType = "text/csv";
    Response.Write("1;computer;1000");
    Response.End();
}

Upvotes: 1

Ram Rajamony
Ram Rajamony

Reputation: 1723

Have you looked at a binary dump of the file to make sure the file being downloaded is identical to the file you're looking at locally? There could be different line terminators being used (e.g. ) that might be causing Excel to tolerantly read it in and display it, but default to saving it as unicode text.

On a Linux (or cygwin) system, using "od -a -x" will tell you how the file is made up.

Upvotes: 0

Related Questions