C#读取CSV文件到DataTable

来源:互联网 发布:梦里花落知多少意思 编辑:程序博客网 时间:2024/05/29 16:34

今天做个小程序,需要批量读取CSV文件到数据库,网上有不少CSVHelper,但是看了下,多少都有点问题,主要是分割逗号问题,还有就是字段处理问题。我自己做了些改良,用起来不错。



using System;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using System.Windows;namespace BtsMaster{ public  class CSVhelper    {                /// <summary>        /// 将Csv读入DataTable        /// </summary>        /// <param name="filePath">csv文件路径</param>        /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>        /// <param name="k">可选参数表示最后K行不算记录默认0</param>        public  DataTable csv2dt(string filePath, int n,DataTable dt) //这个dt 是个空白的没有任何行列的DataTable        {            String csvSplitBy = "(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)";              StreamReader reader = new StreamReader(filePath,  System.Text.Encoding.Default, false);            int i = 0, m = 0;            reader.Peek();            while (reader.Peek() > 0)            {                m = m + 1;                string str = reader.ReadLine();                               if (m >= n + 1)                {                    if (m == n + 1) //如果是字段行,则自动加入字段。                    {                        MatchCollection mcs = Regex.Matches(str, csvSplitBy);                        foreach (Match mc in mcs)                        {                                                       dt.Columns.Add(mc.Value); //增加列标题                        }                                                                 }                    else                    {                        MatchCollection mcs = Regex.Matches(str, "(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");                        i = 0;                        System.Data.DataRow dr = dt.NewRow();                        foreach (Match mc in mcs)                        {                              dr[i] = mc.Value;                            i++;                        }                                              dt.Rows.Add(dr);  //DataTable 增加一行                         }                                    }            }            return dt;        }    }    }

注意,如果CVS文件最后一行不是你想要的,可以通过DataTable.Rows.RemoveAt(RowsCount-1)来删除,比如dt.Rows.RemoveAt(dt.Rows.Count-1)



0 0