Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating/opening CSV from console - file is in wrong format error

I am writing out a comma separated file using a console app, and than using Process to open the file. It's a quick and dirty way of dumping results of a query into excel.

for a while this worked fine, but lately i started getting "The file you are trying to open 'blah.csv', is in a different format than specified by the file extension".

and than after clicking "Yes"

Excel has detected that blah.csv is a SYLK file, but cannot load it. Either the file has errors or it is not a SYLK file format. Click OK to try to open the file in a different format.

Pressing OK opens it, and displays correctly.

I see some solutions for this in web world with adding content-disposition header, but since i am using a Process to open it, i can't apply that fix.

my code to open the file:

ProcessStartInfo info = new ProcessStartInfo(); info.FileName = filePath; info.UseShellExecute = true; Process.Start(info); 

if i open the file in Notepad++ and show all chars, it just shows as regular CSV with CR LF line endings.

after some investigation, it looks like the headings line is triggering the error. If i simply write a empty line before the headings, the error goes away. the headings look like this:

heading1,heading2,heading3 CRLF

like image 232
Sonic Soul Avatar asked Nov 26 '10 15:11

Sonic Soul


People also ask

Why is my CSV not importing correctly?

The most common CSV import errors include: The file size is too large - The CSV import tool of the program you're using might have a file size requirement. To reduce the file size, you can delete unnecessary data values, columns, and rows.

Why does my exported CSV data get converted to weird formats?

Instead, this is due to the way Excel and other spreadsheet programs open a CSV file and display the data therein. Basically, spreadsheet programs are designed to be used for calculation purposes, so they tend to apply mathematical formats to numbers when the CSV file is opened directly into the program.

Why does CSV not save formatting?

Because csv only contains data, not style. If you want to save style save as .


2 Answers

Have a look here: http://support.microsoft.com/kb/323626

it seems having ID as the first two chars on the header row is the issue - pretty bizarre behaviour from Excel in my opinion.

like image 68
John Pickup Avatar answered Sep 18 '22 19:09

John Pickup


The CSV starts with the two characters ID. If you surround the characters with double quotes it should work fine.

like image 29
Jeremy Avatar answered Sep 19 '22 19:09

Jeremy