1. 程式人生 > 實用技巧 >C# 讀取CSV 使用 LumenWorks.Framework.IO

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