简体   繁体   中英

How do I export data to a CSV file in C# making sure that Excel can work with it?

We are exporting a list of dealer information to CSV so the client can work with it in Excel, and import it back into the app.

When we edit the CSV file itself it works perfect, but when Excel opens and saves the file, it loses all CSV structure.

Quotes are removed, and semicolons are removed as well.

Our export code looks like this now:

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment;filename=export_dealers_{0}_{1:yyyy-MM-dd-HH-mm}.csv; charset=utf-8", countryCode, DateTime.Now));
Response.ContentType = "text/csv";
Response.AddHeader("Pragma", "public");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
Response.Write(ToCsv(list));
Response.Flush();
Response.End();

The toCSV function just returns a string with all fields each within quotes, separated with a semicolon.

We had it different before, but had to add extra encoding data, so it doesn't garble up the special characters, like ç or ñ ...

The above piece of code exports a CSV file that seems correct, but when Excel opens it, and saves it (even without changing a field) all semicolons and quotes are removed, and if you try the Save as functionality it detects to save it as a .txt file instead of CSV.

This works just fine for me:

var lines = new string[10][];

var csv = string.Join("\r\n", lines.Select(words =>
              string.Join(",", words.Select(word =>
                  "\"" + word.Replace("\"", "\"\"") + "\"")))));

File.WriteAllText("file.csv", csv);

Excel reads it in it's simplest form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM