You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

37 lines
1.1 KiB

using System;
using System.Data;
using System.IO;
using System.Linq;
namespace ChangkeTec.Utils
{
public static class CsvHelper
{
public static DataTable CsvToDataTable(string csvFileName)
{
DataTable dt = new DataTable();
var lines = File.ReadLines(csvFileName).ToList();
if (lines.Count < 2)
throw new Exception("CSV文件无数据!");
var firstLine = lines[0];
var columnNames = firstLine.Split(',');
foreach (var columnName in columnNames)
{
var dc = new DataColumn(columnName.Trim('\"'));
dt.Columns.Add(dc);
}
for (var i = 1; i < lines.Count; i++)
{
var line = lines[i];
var datas = line.Split(',');
var dr = dt.NewRow();
for (var j = 0; j < datas.Length; j++)
{
dr[j] = datas[j].Trim('\"');
}
dt.Rows.Add(dr);
}
return dt;
}
}
}