利用C# 怎么將TXT文檔轉(zhuǎn)換為Table表格?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
代碼:
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 = ""; //記錄每行記錄中的各字段內(nèi)容 string[] aryLine; //標(biāo)示列數(shù) int columnCount = 0; //標(biāo)示是否是讀取的第一行 bool IsFirst = true; if (IsFirst == true) { //strLine = "ATTENDANCE_DATE,EMP,ATTENDANCE_DEPT,EMP_TYPE,SHITF,PLANT_CODE"; strLine = columnName; aryLine = strLine.Split(','); IsFirst = false; columnCount = aryLine.Length; //創(chuàng)建列 for (int i = 0; i < columnCount; i++) { DataColumn dc = new DataColumn(aryLine[i].ToUpper()); dt.Columns.Add(dc); } } //逐行讀取txt中的數(shù)據(jù) 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; }