Home > Software engineering >  C# saving file as csv is not delimited correctly when viewed in Excel
C# saving file as csv is not delimited correctly when viewed in Excel

Time:03-02

I am using this code to convert my data into a csv file:

 var lines = new List<string>();

 IEnumerable<PropertyDescriptor> props = TypeDescriptor.GetProperties(typeof(T)).OfType<PropertyDescriptor>();

 var header = string.Join(",", props.ToList().Select(x => x.Name));
 lines.Add(header);

 var valueLines = reportData.Select(row => string.Join(",", header.Split(',').Select(a => row.GetType().GetProperty(a).GetValue(row, null))));
 lines.AddRange(valueLines);

But when I view the .csv file afterwards, it looks like this:

enter image description here

So the file is not delimited correctly.

Everything is stored into one column.

The rows are correct however, but again - everything in one column.

I can however then in excel save the file again as "comma delimited Excel csv" and when I open the new file, it shows correct.

So how can I save the file (if not as csv) but instead directly within the correct file format?

CodePudding user response:

Excel use CSV separator based on you region preferences. It seems that separator in your system is ';'. To set custom separator "," for file you need write

sep=,

at first line, so your file must looks like this:

sep=,
Data1, Data2, Data3...
  • Related