当前位置: 代码迷 >> 综合 >> NPOI 读取excel,如果有公式获取公式值
  详细解决方案

NPOI 读取excel,如果有公式获取公式值

热度:36   发布时间:2024-01-21 03:14:11.0
        /// <summary>/// 读取excel ,默认第一行为标头/// </summary>/// <param name="strFileName">excel文档路径</param>/// <returns></returns>public static DataTable ExcelImport(string strFileName){DataTable dt = new DataTable();ISheet sheet = null;using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)){if (strFileName.IndexOf(".xlsx") == -1)//2003{HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);sheet = hssfworkbook.GetSheetAt(0);}else//2007{XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);sheet = xssfworkbook.GetSheetAt(0);}}System.Collections.IEnumerator rows = sheet.GetRowEnumerator();IRow headerRow = sheet.GetRow(0);int cellCount = headerRow.LastCellNum;for (int j = 0; j < cellCount; j++){ICell cell = headerRow.GetCell(j);dt.Columns.Add(cell.ToString());}for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++){IRow row = sheet.GetRow(i);DataRow dataRow = dt.NewRow();for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null){//如果是公式Cell //则仅读取其Cell单元格的显示值 而不是读取公式if (row.GetCell(j).CellType == CellType.Formula){row.GetCell(j).SetCellType(CellType.String);dataRow[j] = row.GetCell(j).StringCellValue;}else{dataRow[j] = row.GetCell(j).ToString();}}}dt.Rows.Add(dataRow);}return dt;}

 

  相关解决方案