用NPOI从Excel到DataTable

NPOI功能强大,不用装Excel,就可以操作表格中数据----Excel.Sheet------>DataTable 

 private IWorkbook workbook = null;
        private ISheet sheet = null;
        private string fileName = "";//文档路径
        private FileStream fs = null;

        public ExcelHelper()
        {
        }
        //构造函数
        public ExcelHelper(string file)
        {
            this.fileName = file;
        }
        /// <summary>
        /// 用NPOI从Excel到DatTable
        /// </summary>
        /// <returns></returns>
        public DataTable ExcelToDataTable()
        {
            DataTable dt = new DataTable();
            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            if (System.IO.Path.GetExtension(fileName) == ".xls")
            {
                workbook = new HSSFWorkbook(fs);
            }
            else if (System.IO.Path.GetExtension(fileName) == ".xlsx")
            {
                workbook = new XSSFWorkbook(fs);
            }
            else
            {
                throw new Exception("文件类型错误");
            }
            sheet = workbook.GetSheetAt(0);
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(0);

                //表头
                for (int i = firstRow.FirstCellNum; i < firstRow.LastCellNum; i++)
                {
                    ICell cell = firstRow.GetCell(i);
                    if (cell != null)
                    {
                        DataColumn column = new DataColumn(cell.StringCellValue);
                        dt.Columns.Add(column);
                    }
                }
                //表数据 Access数据库时,加“等号”-j <= sheet.LastRowNum 
                for (int j = sheet.FirstRowNum + 1; j <= sheet.LastRowNum; j++)
                {
                    IRow row = sheet.GetRow(j);
                    if (row == null)
                    {
                        continue;
                    }
                    DataRow dataRow = dt.NewRow();
                    for (int i = row.FirstCellNum; i < firstRow.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        //加日期处理
                        if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
                        {
                            dataRow[i] = cell.DateCellValue.ToString();
                        }
                        else
                        {
                            dataRow[i] = cell.ToString();
                        }
                    }
                    dt.Rows.Add(dataRow);
                }
            }
            return dt;
        }
View Code

 

转载于:https://www.cnblogs.com/senlinzhang/p/8608708.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值