I'm using LinqToCSV to output a List to CSV. Snippet of sample code is as follows:
class Person
{
[CsvColumn(Name = "Name", FieldIndex = 1)]
public string UserName { get; set; }
[CsvColumn(Name = "Address 1", FieldIndex = 2)]
public string Address1 { get; set; }
[CsvColumn(Name = "Telephone", FieldIndex = 3)]
public string Telephone { get; set; }
}
private void OutputToCSV(string filenamePrefix, List<Person> people)
{
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = ','
FirstLineHasColumnNames = true,
FileCultureName = "en-GB"
};
CsvContext cc = new CsvContext();
cc.Write(
people,
@"C:\temp\people.csv",
outputFileDescription);
}
The issue I have is with the telephone number. If it is in the object as 0123456789012 then when I open the CSV in Excel it is seen as a number and the leading zero is removed. I'd like to pre format the column in the CSV as text.
According to Stop Excel from automatically converting certain text values to dates I can start the field with an equals and put the value in quotes, but is there an attribute I can set which will mean that LinqToCSV will do this for me? I don't really want to use LinqToCSV, then open the file and edit it to get it how I want.
Is your intent to create a CSV or an Excel file? If the latter, then wouldn't it be much easier if you have instead used Epplus from Nuget? ie:
void Main()
{
ExcelPackage pck = new ExcelPackage();
List<Person> people = new List<Person> {
new Person { UserName="Cetin", Address1="A1", Telephone="012345"},
new Person { UserName="Timbo", Address1="A2", Telephone="023456"},
new Person { UserName="StackO", Address1="A3", Telephone="0 345 6789 01 23"},
};
var wsEnum = pck.Workbook.Worksheets.Add("MyPeople");
//Load the collection starting from cell A1...
wsEnum.Cells["A1"].LoadFromCollection(people, true, TableStyles.Medium9);
wsEnum.Cells[wsEnum.Dimension.Address].AutoFitColumns();
//...and save
var fi = new FileInfo(@"d:\temp\People.xlsx");
if (fi.Exists)
{
fi.Delete();
}
pck.SaveAs(fi);
}
class Person
{
public string UserName { get; set; }
public string Address1 { get; set; }
public string Telephone { get; set; }
}