C# 标准读取EXL文件的方式

 

private const string Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";

 public static DataTable ImportExcel()
        {
            var dt = new DataTable();
            var path = GetOpenFile();
            if (string.IsNullOrEmpty(path))
            {
                return null;
            }
            using (var stream = new FileStream(path, FileMode.Open))
            {
                var workbook = GetWorkbook(path, stream);
                var sheet = workbook.GetSheetAt(0);
                var headerRow = sheet.GetRow(0);
                int cellCount = headerRow.LastCellNum;
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                {
                    DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
                    dt.Columns.Add(column);
                }
                int rowCount = sheet.LastRowNum;
                for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null) continue;
                    DataRow dataRow = dt.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
            }
          
            return dt;
        }
        private static string GetOpenFile()
        {
            var openFileDialog = new System.Windows.Forms.OpenFileDialog()
            {
                Filter = Filter
            };
            string filePath = null;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                filePath = openFileDialog.FileName;
            }
            return filePath;
        }
        private static IWorkbook GetWorkbook(string path, FileStream stream)
        {
            if (Path.GetExtension(path).ToLower() == ".xls")
            {
                return stream != null ? new HSSFWorkbook(stream) : new HSSFWorkbook();
            }
            else if (Path.GetExtension(path).ToLower() == ".xlsx")
            {
                return stream != null ? new XSSFWorkbook(stream) : new XSSFWorkbook();
            }

            throw new Exception("异常的后缀");
        }

  • 23
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值