I try to generate CSV file, which contains 4 columns. One of this columns is Name which contains First and Last name separated with space.
When I write this text data to .csv
file, it detect space as comma and add additional column. Example :
Name - First LastName
converts into :
Name | AdditionalColumn
First | LastName
but should be just
Name |
First LastName |
To generate file I use next method :
public string Export(bool includeHeaderLine = true)
{
var sb = new StringBuilder();
//Get properties using reflection.
IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
if (includeHeaderLine)
{
//add header line.
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(propertyInfo.Name).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
//add value for each property.
foreach (T obj in _objects)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(MakeValueCsvFriendly(propertyInfo.GetValue(obj, null))).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
return sb.ToString();
}
First of all, how do check created CSV? If you open it Excell, than first try to modify MakeValueCsvFriendly(object value) and quote value with spaces:
...
if (output.Contains(",") || output.Contains("\"") || output.Contains(" "))
output = '"' + output.Replace("\"", "\"\"") + '"';
...
If you export CSV with header, also, check generated CSV in notepad, do you have double comma after "Name".