讀CSV轉換datatable

using System.Data;spa

using  System.IO;
 
/// <summary>
/// Stream讀取.csv文件
/// </summary>
/// <param name="filePath">文件路徑</param>
/// <returns></returns>
public  static  DataTable OpenCSV( string  filePath)
{
     DataTable dt =  new  DataTable();
     FileStream fs =  new  FileStream(filePath, FileMode.Open, FileAccess.Read);
     StreamReader sr =  new  StreamReader(fs, System.Text.Encoding.Default);
     //記錄每次讀取的一行記錄
     string  strLine =  "" ;
     //記錄每行記錄中的各字段內容
     string [] aryLine;
     //標示列數
     int  columnCount = 0;
     //標示是不是讀取的第一行
     bool  IsFirst =  true ;
     //逐行讀取CSV中的數據
     while  ((strLine=sr.ReadLine())!= null )
     {
         aryLine = strLine.Split( ',' );
         if  (IsFirst== true )
         {
             IsFirst =  false ;
             columnCount = aryLine.Length;
             for  ( int  i = 0; i < columnCount; i++)
             {
                 DataColumn dc =  new  DataColumn(aryLine[i]);
                 dt.Columns.Add(dc);
             }
         }
         else
         {
             DataRow dr = dt.NewRow();
             for  ( int  j = 0; j < columnCount; j++)
             {
                 dr[j] = aryLine[j];
             }
             dt.Rows.Add(dr);
         }
     }
     sr.Close();
     fs.Close();
     return  dt;
}
相關文章
相關標籤/搜索