Reputation: 24799
I've created a .csv file using C# and when I open this file in Excel, it shows the double quotes in the cells.
When I open the csv in Notepad++ I see that are quotes are there and everything looks right to me. Here's a part of my csv:
"CertificaatNummer", "Data", "Inleg", "Getekend", "Ingangsdatum", "Betaalmethode", "Status", "Bonus", "Aankoopkoers", "Korting", "Garantiewaarde", "Betaalde termijnen", "Inleg nominaal", "Tweede naam", "Recht op bonus maand", "Begunstigde", "Product", "Incasserekening", "Uitbetaalrekening"
"126136", "some data with, a comma", "118.34", "True", "28-1-1999 00:00:00", "Cash", "C02", "0.00", "531,940", "0,000", "0.00", "0", "0.00", "", "False", "P.H. Bloemink", "Cash-Click", "", "260952095"
"137190", "other data", "0.00", "True", "23-12-1999 00:00:00", "Cash", "C02", "0.00", "660,620", "0,000", "0,00"
When I open this file in Excel it treats the comma in some data with, a comma
as a new column. So I get "Some data with
in one cell and a comma"
in antother cell. As you see, Excel doesn't care about the double quotes.
Here's what my code looks like (simplified):
var content = new List<string>();
// Add headers
content.Add("\"Header 1\", \"Header 2\", \"Header 3\", \"Header 4\"");
// Add content
content.Add("\"123456\", \"some data with, a comma\", \"118.34\", \"True\"");
// etc..
// I let a function create my file content
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
foreach (var line in this.content)
{
writer.WriteLine(line);
}
writer.Flush();
return stream.ToArray();
}
// finally I return the file content to the browser with
// HttpContext.Response.AddHeader("content-disposition", "file;name=" + fileName);
The question is, which part of my code do I have to edit so Excel will display my file properly? I rather want to edit my code then executing some tricks in Excel.
Upvotes: 6
Views: 5279
Reputation: 60344
The problem seems to be spaces after the comma separators.
Instead of
"some, text","Other text"
your code is generating:
"some, text",<space>"Other text"
So the Excel CSV importer is getting flummoxed. Remove those extra spaces and you should be OK.
Upvotes: 14
Reputation: 6183
Some time ago, I found out that Excel likes its CSV files UTF-16LE encoded, with tabs (ASCII code 9) as delimiters. It even accepts (and removes) double quotes around the values.
Upvotes: 1
Reputation: 112
Just reflect comma with "\" symbol.
Or if you doing it programmatically just fire Replace(",","\,")
method
Upvotes: 0