把 Csv 文件转化为数据表

/// <summary>
    /// 操作 Csv 文件的辅助类
    /// </summary>
    /// <remarks>
    ///     创建:宋飞 2013-3-18
    /// </remarks>
    public class CsvHelper
    {
        /// <summary>
        /// 把 Csv 文件转化为数据表
        /// </summary>
        /// <param name="file">csv 文件</param>
        /// <returns>数据表</returns>
        public static DataTable ToDataTable(string file)
        {
            DataTable dt = new DataTable();

            if (!File.Exists(file))
                throw new FileNotFoundException("要读取的 csv 文件不存在,请检测路径 " + file + " 是否正确!");
            string[] arr = File.ReadLines(file,Encoding.Default).ToArray();
            if (arr.Length > 0)
            {
                //读取列
                string[] head = arr[0].Replace("\"", "").Split(',');
                for (int i = 0; i < head.Length; i++)
                {
                    DataColumn column = new DataColumn(head[i].Trim());
                    dt.Columns.Add(column);
                }
                //读取行
                for (int i = 1; i < arr.Length; i++)
                {
                    DataRow row = dt.NewRow();
                    string[] content = arr[i].Replace("\"", "").Split(',');
                    for (int j = 0; j < content.Length; j++)
                        row[j] = content[j];
                    dt.Rows.Add(row);
                }
            }
            else
            {
                throw new Exception("文件没有数据!");
            }

            return dt;
        }
    }

  

转载于:https://www.cnblogs.com/felixsung/archive/2013/04/23/3037634.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值