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;
                    }
                }
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM