歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

C#讀取CSV文件的方法

在很多系統中,都需要讀取csv文件,我在以前的一個項目中也遇到過要將csv文件中的數據讀取到datatable中進行處理,下面的代碼

是我以前寫的將csv文件中的數據導入到DataTable中的方法,現在貼出來給大家分享:

//GetCSVFile'S FileName and Data獲取csv文件中數據,並將數據導入DataTable中

// mycsvdt 用來裝csv文件中數據的datatable,filepath是指csv文件的路徑


private bool OpenCSVFile(ref DataTable mycsvdt,string filepath)
        {
            string strpath = filepath; //csv文件的路徑
            try
            {
                int intColCount = 0;
                bool blnFlag = true;

                DataColumn mydc;
                DataRow mydr;
               
                string strline;
                string [] aryline;
                StreamReader mysr = new StreamReader(strpath,System.Text.Encoding.Default);

                while((strline = mysr.ReadLine()) != null)
                {
                    aryline = strline.Split(new char[]{','});

                    //給datatable加上列名
                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        int col=0;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            col=i+1;
                            mydc = new DataColumn(col.ToString());
                            mycsvdt.Columns.Add(mydc);
                        }
                    }

                    //填充數據並加入到datatable中
                    mydr = mycsvdt.NewRow();
                    for (int i = 0; i < intColCount; i++)
                    {
                        mydr[i] = aryline[i];
                    }
                    mycsvdt.Rows.Add(mydr);
                }
                return true;

            }
            catch (Exception e)
            {
               
               
                throw (Stack.GetErrorStack(strpath+"讀取CSV文件中的數據出錯." + e.Message, "OpenCSVFile("));
                return false;
            }
        }

Copyright © Linux教程網 All Rights Reserved