C# 實現TXT文檔轉 代碼: public DataTable TXTToDataTable(string fileName, string columnName) { DataTable dt = new DataTable(); FileStream fs = new FileStream(f ...
C# 實現TXT文檔轉
代碼:
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) { //strLine = "ATTENDANCE_DATE,EMP,ATTENDANCE_DEPT,EMP_TYPE,SHITF,PLANT_CODE"; 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; }