本文執行個體講述了asp.net實現從Txt檔案讀取資料到資料檢視的方法。分享給大家供大家參考,具體如下:
#region 從Txt檔案讀取資料到資料檢視/// 從Txt檔案讀取資料到資料檢視/// </summary>/// <param name="strExcelPath">檔案路徑</param>/// <returns>返回一個資料檢視</returns>public static DataView GetDataFromTxt(string strTxtPath){ string strLine = ""; DataRow row; try { DataTable tbl = new DataTable(); StreamReader sr = new StreamReader(strTxtPath, Encoding.GetEncoding("GB2312")); strLine = sr.ReadLine(); //讀取第一行列屬性 string[] Fields = strLine.Split(new char[] { '/t' });//讀取每一個欄位(以TAB分開) for (int k = 0; k < Fields.Length; k++) //給表增加列屬性 { tbl.Columns.Add(Fields[k], typeof(string)); } while ((strLine = sr.ReadLine()) != null) { row = tbl.NewRow(); string[] words = strLine.Split(new char[] { '/t' });//讀取每一個欄位值(以TAB分開) for (int j = 0; j < words.Length; j++) { row[j] = words[j]; } tbl.Rows.Add(row); } sr.Dispose(); sr.Close(); DataView dv = new DataView(tbl); return dv; } catch { return null; }}#endregion
希望本文所述對大家asp.net程式設計有所協助。