原文引用:https://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
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;
/// <summary>
/// 獲取路徑下的.csv文件
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static DataTable GetStream(string FilePath)
{
FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
Stream stream = new MemoryStream(bytes);
return GetData(stream);
}
/// <summary>
/// 將.csv文件轉換成DataTable
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
private static DataTable GetData(Stream stream)
{
using (stream)
{
using (StreamReader input = new StreamReader(stream, Encoding.GetEncoding("GBK")))
{
using (CsvReader csv = new CsvReader(input, true))
{
DataTable dt = new DataTable();
//第一行字段數量
int columnCount = csv.FieldCount;
//標題數組
string[] headers = csv.GetFieldHeaders();
//循環添加標題行
for (int i = 0; i < columnCount; i++)
{
dt.Columns.Add(headers[i]);
}
//循環添加列數據
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;
}
}
}
}
我只是參考原文里面的實例,根據我項目的需求換了一種寫法,換湯不換葯(先看明白簡單的CsvReader對.csv標題和列的操作然后根據自身的需求去改寫,主要改也是簡單的循環或者根據解析格式不同換一種格式其它的看需求調整。),希望對大家有所幫助,共同學習!
