public static DataTable ImportCSV(string filePath)
{
DataTable dt = new DataTable();
int lsi = 0;
char cv = '\r';
bool HeadYes = true;//第一行是否为标题
StreamReader fileReader = new StreamReader(filePath, Encoding.Default);
while (fileReader.EndOfStream == false)
{
string line = fileReader.ReadLine();
string[] y = line.Split(cv);
//第一行为标题行
if (HeadYes == true)
{
//第一行
if (lsi == 0)
{
for (int i = 0; i < y.Length; i++)
{
dt.Columns.Add(y[i].Trim().ToString());
}
lsi++;
}
//从第二列开始为数据列
else
{
DataRow dr = dt.NewRow();
for (int i = 0; i < y.Length; i++)
{
dr[i] = y[i].Trim();
}
dt.Rows.Add(dr);
}
}
//第一行不为标题行
else
{
if (lsi == 0)
{
for (int i = 0; i < y.Length; i++)
{
dt.Columns.Add(i.ToString());
}
lsi++;
}
DataRow dr = dt.NewRow();
for (int i = 0; i < y.Length; i++)
{
dr[i] = y[i].Trim();
}
dt.Rows.Add(dr);
}
}
return dt;
}