c#读取CSV文件跟Excel导入成DataTble

1.读取CSV文件

  /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        public static DataTable ReadCSV(string fileName)
        {
   
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8, false);

            //记录每次读取的一行记录
            string strLine = null;
            //记录每行记录中的各字段内容
            string[] arrayLine = null;
            //判断,若是第一次,建立表头
            bool isFirst = true;

            //列的个数
            int dtColumns = 0;

            //逐行读取CSV文件
            while ((strLine = sr.ReadLine()) != null)
            {
   
                strLine = strLine.Trim();//去除头尾空格
                arrayLine = strLine.Split(',');//分隔字符串,返回数组

                if (isFirst)  //建立表头
                {
   
                    dtColumns = arrayLine.Length;//列的个数
                    for (int i = 0; i < dtColumns; i++)
                    {
   
                        dt.Columns.Add(arrayLine[i]);//每一列名称
                    }
                    isFirst = false;
                }
                else   //表内容
                {
   
                    DataRow dataRow = dt.NewRow();//新建一行
                    for (int j = 0; j < dtColumns; j++)
                    {
   
                        if (arrayLine.Length > j)
                        {
   
                            dataRow[j] = arrayLine[j];
                        }
                    }
                    dt.Rows.Add(dataRow);//添加一行
                }
            }
            sr.Close();
            fs.Close();

            return dt;
        }

2.Excel导入成DataTble

    /// <summary>
        /// Excel导入成DataTble
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static DataTable ExcelToTable(string file)
        {
   
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
   
                if (fileExt == ".xlsx") {
    workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") {
    workbook = new HSSFWorkbook(fs); } else {
    workbook = null; }
                if (workbook == null) {
    return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
   
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
   
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
   
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
   
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
   
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
   
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell">目标单元格</param>
        /// <returns></returns>
        private static object GetValueType(ICell cell)
        {
   
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
   
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }

相关推荐

  1. c#读取CSV文件Excel导入DataTble

    2023-12-16 23:38:02       52 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-16 23:38:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-16 23:38:02       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-16 23:38:02       82 阅读
  4. Python语言-面向对象

    2023-12-16 23:38:02       91 阅读

热门阅读

  1. Python实现数据库导出Excel并动态化sql时间

    2023-12-16 23:38:02       52 阅读
  2. 数据库基础学习04计算机二级-第四章 数据查询

    2023-12-16 23:38:02       55 阅读
  3. 条件诱导:Python中的条件语句详解

    2023-12-16 23:38:02       66 阅读
  4. C语言—每日选择题—Day51

    2023-12-16 23:38:02       58 阅读
  5. libevent入门教程

    2023-12-16 23:38:02       58 阅读
  6. C#基础——字符串、字符串API。可变字符串

    2023-12-16 23:38:02       56 阅读
  7. AI write rust code

    2023-12-16 23:38:02       51 阅读
  8. 【设计模式】之单例模式

    2023-12-16 23:38:02       56 阅读
  9. 华为云CodeArts Deploy常见问答汇总

    2023-12-16 23:38:02       56 阅读
  10. Docker常用管理命令

    2023-12-16 23:38:02       40 阅读