在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C#实现TXT文档转DataTable代码: public DataTable TXTToDataTable(string fileName, string columnName) { DataTable dt = new DataTable(); FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default); //记录每次读取的一行记錄 string strLine = ""; //記錄每行記錄中的各字段内容 string[] aryLine; //标示列数 int columnCount = 0; //标示是否是读取的第一行 bool IsFirst = true; if (IsFirst == true) { if (columnName=="") { //说明txt包含列名时,不传入列名,用过读取获得列名,一般用tab分隔 strLine = sr.ReadLine(); aryLine = strLine.Split('\t');//tab分隔符 } else { strLine = columnName; aryLine = strLine.Split(',');//传入列名用逗号分隔 } IsFirst = false; columnCount = aryLine.Length; //创建列 for (int i = 0; i < columnCount; i++) { DataColumn dc = new DataColumn(aryLine[i].ToUpper()); dt.Columns.Add(dc); } } //逐行读取txt中的数據 while ((strLine = sr.ReadLine()) != null) { aryLine = strLine.Split('\t');//tab分隔符 DataRow dr = dt.NewRow(); for (int j = 0; j < columnCount; j++) { dr[j] = aryLine[j].ToUpper(); } dt.Rows.Add(dr); } sr.Close(); fs.Close(); return dt; } |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论