原文引用: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标题和列的操作然后根据自身的需求去改写,主要改也是简单的循环或者根据解析格式不同换一种格式其它的看需求调整。),希望对大家有所帮助,共同学习!