zoukankan      html  css  js  c++  java
  • 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;
                        }
                    }
                }
            }
        }
    }
  • 相关阅读:
    监听键盘弹出 隐藏
    状态栏 设置白色字体
    UITextField 属性详解
    支付宝集成SDK 报错
    UIWebView
    app上传 需要的icon
    百度云推送 pem
    百度地图
    info.plist 属性讲解
    静态库 动态库
  • 原文地址:https://www.cnblogs.com/houzf/p/13636808.html
Copyright © 2011-2022 走看看