软件编程
位置:首页>> 软件编程>> C#编程>> C# 实现TXT文档转Table的示例代码

C# 实现TXT文档转Table的示例代码

作者:農碼一生  发布时间:2022-04-23 07:47:52 

标签:c#,txt,文档,table

代码:


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;
   }

来源:https://www.cnblogs.com/wml-it/p/13195101.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com