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;
    }
  • 相关阅读:
    mvc 在ii7上发布时遇到的问题只解决
    @Html.Raw 显示Html的标签
    补发————grid布局
    补发————DOM与BOM
    web实验博客3.css-position
    web专业课学习及往后方向发展
    bom&dom
    网格代码
    简单用户注册表单
    自我介绍
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/9625417.html
Copyright © 2011-2022 走看看