C# CSV 文件读取的三种方式分析

1 、文件流 + 字符串分割(“,”),缺点:数据中如果有“,”,会出现分割错误。

public DataTable readCsvSql(string filepath)
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
    //记录每次读取的一行记录
    string strLine = null;
    //记录每行记录中的各字段内容
    string[] arrayLine = null;
    //分隔符
    string[] separators = { ",","\t"};
    //逐行读取CSV文件
    while ((strLine = sr.ReadLine()) != null)
    {
         //去除头尾空格
          strLine = strLine.Trim();
          //分隔字符串,返回数组
          arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);

          // arrayLine  就是需要的数据
    }
}
                    

2、  读取数据库表方式

缺点:不同系统上的 Provider 值不一样,没法大面积使用 (Provider=Microsoft.Jet.OLEDB.4.0; 这个在win7上可行,网上说win11有问题)

 public DataTable readCsvSql(string filepath)
        {
            DataTable dt = new DataTable();
            try
            {
                string directory = Path.GetDirectoryName(filepath);
                string file = Path.GetFileName(filepath);

                if (file.Trim().ToUpper().EndsWith("CSV"))//判断所要读取的扩展名
                {
                    string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + directory + ";Extended Properties='text;HDR=NO;FMT=Delimited'";//有列的读取
                    string commandText = "select * from [" + file + "]";//SQL语句
                    OleDbConnection olconn = new OleDbConnection(connStr);
                    olconn.Open();
                    OleDbDataAdapter odp = new OleDbDataAdapter(commandText, olconn);
                    odp.Fill(dt);
                    olconn.Close();
                    odp.Dispose();
                    olconn.Dispose();
                }
                else
                {
                    //  异常处理
                }
            }
            catch (Exception ex)
            {
                //  异常处理
            }

            return dt;
        }

3. 使用 FileIO.TextFieldParser读取, 我现在就采用这个方法,暂时没发现问题 。


        private void ReadCSVFile(string strCsvFilePath)
        {
            using (Microsoft.VisualBasic.FileIO.TextFieldParser csvReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(strCsvFilePath, Encoding.GetEncoding("gb2312")))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                csvReader.TrimWhiteSpace = true;
                // 跳过标题行(如果有)
                //csvReader.ReadLine();

                while (!csvReader.EndOfData)
                {
                    string[] arrayLine = csvReader.ReadFields();                
                    // arrayLine 中就是每行的数据

                }  
            }
        }

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值