C# CSV 文件转换成DataTable

时间:2022-04-03 00:08:41
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
//记录每次读取的一行记录
string strLine = "";
//记录每行记录中的各字段内容
string[] aryLine;
//标示列数
int columnCount = 0;
//标示是否是读取的第一行
bool IsFirst = true;
bool IsTotalResult = false;
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
if (strLine == "" || strLine.Replace(",","").IsEmpty())
{
continue;
}
aryLine = strLine.Replace(" ","").Split(',');
if (strLine.Contains("Header_Data"))
{
IsTotalResult = true;
continue;
}
if (IsTotalResult)
{
if (strLine.Contains("Component_Data"))
{
string totalReuslt = dt.Rows[0]["Result"].ToString();
strSN = dt.Rows[0]["BarCode"].ToString();
if (totalReuslt.Contains('F'))
{
IsTotalResult = false;
dt = new DataTable();
IsFirst = true;
continue;
}
else
{
sr.Close();
fs.Close();
return true;
}
}
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i].Trim());
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j].Trim();
}
dt.Rows.Add(dr);
}
continue;
}
if (IsFirst == true)
{
IsFirst = false;
columnCount = aryLine.Length;
//创建列
for (int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(aryLine[i].Trim());
dt.Columns.Add(dc);
}
}
else
{
DataRow dr = dt.NewRow();
for (int j = 0; j < columnCount; j++)
{
dr[j] = aryLine[j].Trim();
}
dt.Rows.Add(dr);
}
}
sr.Close();
fs.Close();
}