• 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;
                        }
                    }
                }
            }
        }
    }
  • 相关阅读:
    Redis12:客户端
    Redis11:事件
    Redis10:RDB持久化与AOF持久化
    Redis09:过期时间与删除策略、redis中的特殊线程
    Redis08:redis中的对象与存储形式
    Redis07:底层:基数树radix tree
    Redis06:底层:跳跃链表skiplist
    C++基础知识:异常处理
    C++基础知识:STL简介
    C++基础知识:泛型编程
  • 原文地址:https://www.cnblogs.com/houzf/p/13636808.html
Copyright © 2020-2023  润新知