C# 读取CSV 使用 LumenWorks.Framework.IO

1、Nuget 安装LumenWorks.Framework.IO

 

 添加帮助类代码如下:

using LumenWorks.Framework.IO.Csv;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlightAirlineCompare.Logic
{
    public class ReaderCsv
    {
        public static DataTable CsvToTable(string path, int titleCount)
        {
            if (File.Exists(path))
            {
                return ReadCsv(path, titleCount);
            }
            else
            {
                throw new Exception(path + "文件不存在!");
            }
        }

       /// <summary>
       /// 读取CSV
       /// </summary>
       /// <param name="path">路径</param>
       /// <param name="titleCount">表头占用行数</param>
       /// <returns></returns>

private static DataTable ReadCsv(string path, int titleCount)
        {
            //如果遇到中文乱码情况可以设置一下编码字符集
            Encoding _encode = Encoding.GetEncoding("GB2312");
            Stream stream = File.OpenRead(path);
            using (stream)
            {
                using (StreamReader input = new StreamReader(stream, _encode))
                {
                    using (CsvReader csv = new CsvReader(input, false))
                    {
                        DataTable dt = new DataTable();
                        int columnCount = csv.FieldCount;

                        for (int i = 0; i < titleCount; i++)
                        {
                            csv.ReadNextRecord();
                        }
                        for (int i = 0; i < columnCount; i++)
                        {
                            dt.Columns.Add(csv[i].ToString());
                        }
                        while (csv.ReadNextRecord())
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < columnCount; i++)
                            {
                                if (!string.IsNullOrWhiteSpace(csv[i]))
                                {
                                    dr[i] = csv[i];
                                }
                            }
                            dt.Rows.Add(dr);
                        }
                        return dt;
                    }
                }
            }
        }
    }
}

 

posted @ 2020-09-09 07:51  吃葡萄不吐葡萄脾  阅读(796)  评论(0编辑  收藏  举报