在很多系统中,都需要读取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;
            }
        }