首页 > 其他分享 > NPOI读取Excel表格

NPOI读取Excel表格

时间:2023-03-30 12:14:49浏览次数:48  
标签:string int Excel NPOI headerRowIndex openFileDig DataTable 读取

下面是根据实际使用中截取的部分关键代码

public class ImportFromExcel : ExcelHelperBase
    {
        /// <summary>
        /// 读取Excel表格信息.
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="sheetName">Excel工作表名称</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public override DataTable ImportFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
        { 
            using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
            {
                bool isCompatible = GetIsCompatible(excelFilePath);
                return ImportFromExcel(stream, sheetName, headerRowIndex, isCompatible);
            }
        }

        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFileStream">Excel文件流</param>
        /// <param name="sheetName">Excel工作表名称</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <param name="isCompatible">是否为兼容模式</param>
        /// <returns>DataTable</returns>
        public DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible)
        {
            IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
            ISheet sheet = null;
            int sheetIndex = -1;
            if (int.TryParse(sheetName, out sheetIndex))
            {
                sheet = workbook.GetSheetAt(sheetIndex);
            }
            else
            {
                sheet = workbook.GetSheet(sheetName);
            }

            DataTable table = GetDataTableFromSheet(sheet, headerRowIndex); 

            excelFileStream.Close();
            workbook = null;
            sheet = null;
            return table;
        }

        /// <summary>
        /// 从工作表中生成DataTable
        /// </summary>
        /// <param name="sheet">Excel工作表</param>
        /// <param name="headerRowIndex">索引</param>
        /// <returns></returns>
        private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex)
        {
            DataTable table = new DataTable();

            // 展示字段
            BomGenericFields.BomDisplayFiled = sheet.GetRow(0).GetCell(0)?.StringCellValue?.Trim();

            // 标题行
            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellCount = headerRow.LastCellNum;
            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
                {
                    // 如果遇到第一个空列,则不再继续向后读取
                    cellCount = i;
                    break;
                }
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }

            for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
            {
                // BOM excel的特殊处理
                if (i == 3)
                {
                    continue;
                }

                IRow row = sheet.GetRow(i);
                int x = row.Count();
                //如果遇到某行的第一个单元格的值为空,则不再继续向下读取
                if (row != null && row.Count() > 0 && !string.IsNullOrEmpty(row.GetCell(0)?.ToString()))
                {
                    DataRow dataRow = table.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        dataRow[j] = x <= 0 ? null : row.GetCell(j)?.ToString();
                        x--;
                    }

                    table.Rows.Add(dataRow);
                }
            }

            return table;
        }

    }

基类:

  public class ExcelHelperBase
    {
        /// <summary>
        /// 由Excel导入DataTable
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="sheetName">Excel工作表名称</param>
        /// <param name="headerRowIndex">Excel表头行索引</param>
        /// <returns>DataTable</returns>
        public virtual DataTable ImportFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
        {
            return null;
        }

        /// <summary>
        /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable
        /// </summary>
        /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
        /// <param name="headerRowIndex">Excel表头行索引</param> 
        /// <param name="sheets">sheet集合</param>
        /// <returns>DataSet</returns>
        public virtual DataSet ImportFromExcel(string excelFilePath, int headerRowIndex, List<string> sheets)
        {
            return null;
        }

        /// <summary>
        /// 获取要打开要导入的文件名称(含完整路径)
        /// </summary>
        /// <returns></returns>
        protected string GetOpenFilePath()
        {
            OpenFileDialog openFileDig = new OpenFileDialog();
            openFileDig.Filter = "Excel Office  -   (*.xls)|*.xls|Excel Office    及以上(*.xlsx)|*.xlsx";
            openFileDig.FilterIndex = 0;
            openFileDig.Title = "打开";
            openFileDig.CheckFileExists = true;
            openFileDig.CheckPathExists = true;
            //   openFileDig.InitialDirectory = Common.DesktopDirectory;
            string filePath = null;
            if (openFileDig.ShowDialog() == DialogResult.OK)
            {
                filePath = openFileDig.FileName;
            }

            return filePath;
        }

        /// <summary>
        /// 判断是否为兼容模式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected bool GetIsCompatible(string filePath)
        {
            return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 创建工作薄(依据文件流)
        /// </summary>
        /// <param name="isCompatible"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        protected static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
        {
            if (isCompatible)
            {
                return new HSSFWorkbook(stream);
            }
            else
            {
                return new XSSFWorkbook(stream);
            }
        }
    }

 

标签:string,int,Excel,NPOI,headerRowIndex,openFileDig,DataTable,读取
From: https://www.cnblogs.com/anjingdian/p/17272080.html

相关文章