把CSV文件读到一个DataTable中

在处理CSV文件的时候发现,不能简单的用逗号来拆分内容,如果在双引号里面有逗号,那么这行将解析错误。最后找到个用正则表达式来splite的简单方面。原理就是用 ","来作为拆分的标记。

         ///   <summary>
        
///  把一个CSV文件读到一个DataTable中
        
///   </summary>
        
///   <param name="strpath"> 文件完整路径 </param>
        
///   <returns> DataTable </returns>
         public   static  DataTable GetTable( string  strpath)
        {
            Regex reg 
=   new  Regex( " \ " ,\ "" );
            
int  intColCount  =   0 ;
            DataTable mydt 
=   new  DataTable( " myTableName " );

            
// DataColumn mydc;
            
// DataRow mydr;

            
// string strpath = "";
             string  strline;
            
string [] aryline;

            StreamReader mysr 
=   new  StreamReader(strpath,System.Text.Encoding.Default);
            strline 
=  mysr.ReadLine();

            aryline 
=  reg.Split(strline);

            intColCount 
=  aryline.Length;
            
for  ( int  i  =   0 ; i  <  aryline.Length; i ++ )
            {
                DataColumn mydc 
=   new  DataColumn(aryline[i].Replace( " \ "" "" ), typeof(string));
                mydt.Columns.Add(mydc);
            }
            
            
while  ((strline  =  mysr.ReadLine())  !=   null )
            {
                aryline 
=  reg.Split(strline);
                
                DataRow mydr 
=  mydt.NewRow();
                
for  ( int  i  =   0 ; i  <  intColCount; i ++ )
                {
                    mydr[i] 
=  aryline[i].Replace( " \ "" , "" );
                }
                mydt.Rows.Add(mydr);
            }
            
return  mydt;
        }
发布了67 篇原创文章 · 获赞 0 · 访问量 1796

猜你喜欢

转载自blog.csdn.net/format_km/article/details/93031483