zoukankan      html  css  js  c++  java
  • 读CSV转换datatable

    using System.Data;

    using System.IO;
     
    /// <summary>
    /// Stream读取.csv文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <returns></returns>
    public static DataTable OpenCSV(string filePath)
    {
        DataTable dt = new DataTable();
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
        //记录每次读取的一行记录
        string strLine = "";
        //记录每行记录中的各字段内容
        string[] aryLine;
        //标示列数
        int columnCount = 0;
        //标示是否是读取的第一行
        bool IsFirst = true;
        //逐行读取CSV中的数据
        while ((strLine=sr.ReadLine())!=null)
        {
            aryLine = strLine.Split(',');
            if (IsFirst==true)
            {
                IsFirst = false;
                columnCount = aryLine.Length;
                for (int i = 0; i < columnCount; i++)
                {
                    DataColumn dc = new DataColumn(aryLine[i]);
                    dt.Columns.Add(dc);
                }
            }
            else
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < columnCount; j++)
                {
                    dr[j] = aryLine[j];
                }
                dt.Rows.Add(dr);
            }
        }
        sr.Close();
        fs.Close();
        return dt;
    }
  • 相关阅读:
    网络流(平面图转对偶图)
    666
    期望总结
    docker-1-简介
    22、整合mybatis
    21、整合Druid数据源
    20、Springboot 与数据访问(JDBC/自动配置)
    19、配置嵌入式servlet容器(下)
    18、配置嵌入式servlet容器(2)
    17、配置嵌入式servlet容器(1)
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/9625417.html
Copyright © 2011-2022 走看看