【C#】读取txt文件数据并转为DataTable表格数据

 public static DataTable ReadDataTable(string filePath)
 {
     DataTable dt = new DataTable();
     StreamReader sR = null;
     try
     {
         if (File.Exists(filePath))
         {
             sR = File.OpenText(filePath);
             //记录每次读取的一行记录
             string nextLine = "";
             //记录每行记录中的各字段内容
             string[] aryLine = null;
             string[] tableHead = null;
             //标示列数
             int columnCount = 0;
             //标示是否是读取的第一行
             bool IsFirst = true;
             while ((nextLine = sR.ReadLine()) != null)
             {
                 if (IsFirst == true)
                 {
                     tableHead = nextLine.Split(',');
                     IsFirst = false;
                     columnCount = tableHead.Length;
                     //创建列
                     for (int i = 0; i < columnCount; i++)
                     {
                         DataColumn dc = new DataColumn(tableHead[i]);
                         dt.Columns.Add(dc);
                     }
                 }
                 else
                 {
                     aryLine = nextLine.Split(',');
                     DataRow dr = dt.NewRow();
                     for (int j = 0; j < columnCount; j++)

                     {
                         dr[j] = aryLine[j];
                     }
                     dt.Rows.Add(dr);
                 }
             }
         }
     }
     catch (Exception ex)
     {
     }
     finally
     {
         if (sR != null)
             sR?.Close();
     }
     return dt;
 }
posted @ 2024-12-10 16:48  qiutian-hao  阅读(1)  评论(0编辑  收藏  举报