首页
科技
登录
6mi
u
盘
搜
搜 索
科技
C# CSV 文件转换成DataTable
C# CSV 文件转换成DataTable
it
2022-05-29
57
{ 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(); }
转载于:https://www.cnblogs.com/ILoveMyJob/p/10137292.html
相关资源:DataTable与CSV文件互转
转载请注明原文地址: https://win8.8miu.com/read-1497072.html
专利
最新回复
(
0
)