using Microsoft.VisualBasic.FileIO;
public static DataTable GetDataTabletFromCsvFile(string csvFilePath)
{
DataTable csvData = new DataTable();
using (TextFieldParser csvReader = new TextFieldParser(csvFilePath,Encoding.UTF7))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
//read column names
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
return csvData;
}
Wednesday, December 17, 2014
C# CSV to Datatable
Add reference of Microsoft.VisualBasic which would enable TextFieldParser class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment