C# 读取CSV数据

/// <summary>
/// 读取CSV文件
/// </summary>
/// <param name="filePath">文件路径 eg:D:\A.csv</param>
/// <param name="dt">数据(无标题)</param>
/// <param name="csvTitles">标题</param>
public static bool ReadCSV(string filePath, out DataTable dt, out ArrayList csvTitles)
{
    dt = new DataTable();
    csvTitles = new ArrayList();
    try
    {
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
        //记录每次读取的一行记录
        string strLine = null;
        //记录每行记录中的各字段内容
        string[] arrayLine = null;
        //分隔符
        string[] separators = { "," };
        //表头标志位(若是第一次,建立表头)
        bool isFirst = true;
        //逐行读取CSV文件
        while ((strLine = sr.ReadLine()) != null)
        {
            //去除头尾空格
            strLine = strLine.Trim();
            //分隔字符串,返回数组
            arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            //建立表头
            if (isFirst)  
            {
                for (int i = 0; i < arrayLine.Length; i++)
                {
                    dt.Columns.Add(arrayLine[i]);//每一列名称
                    csvTitles.Add(arrayLine[i]);
                }
                isFirst = false;
            }
            else   //表内容
            {
                DataRow dataRow = dt.NewRow();//新建一行
                for (int j = 0; j < arrayLine.Length; j++)
                {
                    dataRow[j] = arrayLine[j];
                }
                dt.Rows.Add(dataRow);//添加一行
            }
        }
        sr.Close();
        fs.Close();
        return true;
    }
    catch
    {
        return false;
    }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值