编程语言
首页 > 编程语言> > c# 将csv文件转换datatable的两种方式。

c# 将csv文件转换datatable的两种方式。

作者:互联网

第一种:

public static DataTable csvdatatable(string path)
{
DataTable dt = new DataTable();
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;MAXSCANROWS=0'"using (OleDbConnection conn = new OleDbConnection(connectionString))
{
using (OleDbCommand comm = new OleDbCommand())
{
string sheetName = "Sheet1";
comm.CommandText = "Select * from [" + sheetName + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}

}
}

第二种:

需要引用    

Microsoft.VisualBasic.dll

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
if (column == "Date" || column == "Test1" || column == "USL" || column == "LSL")
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}

}
catch (Exception)
{
throw;
}
return csvData;
}

标签:csvReader,string,c#,DataTable,column,new,csv,datatable,fieldData
来源: https://www.cnblogs.com/jack-jun/p/10677966.html