使用Java POI將Excel表格變成HTML表格
- 我是將標籤的css與屬性當做引數傳入,大家可以按需修改,下面是解析Excel表格的方法,主要是解析單元格的跨行與跨列,然後拼成一個字串輸出
public static void readXls(File file, StringBuffer html, EditExcel editExcel) { try { HashMap<String, String> mergedRegion = new HashMap<>(); POIFSFileSystem poifsFileSystem = new POIFSFileSystem( new FileInputStream(file)); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem); HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0); int rowLength = hssfSheet.getLastRowNum() + 1; HSSFRow hssfRow; HSSFCell hssfCell; int[] countcolpanNum = new int[50]; int colspanlength = 0; int firstColumn, lastColumn, firstRow, lastRow; CellRangeAddress ca; for (int i = 0; i < hssfSheet.getNumMergedRegions(); i++) { ca = hssfSheet.getMergedRegion(i); firstColumn = ca.getFirstColumn(); lastColumn = ca.getLastColumn(); firstRow = ca.getFirstRow(); lastRow = ca.getLastRow(); mergedRegion.put(firstRow + “&” + firstColumn, (lastColumn - firstColumn + 1) + “&” + (lastRow - firstRow + 1)); }
for (int i = 0; i < rowLength; i++) { if (hssfSheet.getRow(i) != null) { colspanlength = hssfSheet.getRow(i).getLastCellNum(); break; } } for (int i = 0; i < rowLength; i++) { hssfRow = hssfSheet.getRow(i); if (hssfRow != null) { HtmlTr.writeStart(html, CssString.TR_CLASS, CssString.TR_STYLE, CssString.NULL_VALUE, editExcel); for (int j = 0; j < hssfRow.getLastCellNum(); j++) { hssfCell = hssfRow.getCell(j); if (hssfCell != null) { hssfCell.setCellType(CellType.STRING); if (!"".equals(hssfCell.getStringCellValue())) { int colspan = 1; int rowspan = 1; if (mergedRegion.containsKey(i + "&" + j)) { String temp = mergedRegion.get(i + "&" + j); int tempInt = mergedRegion.get(i + "&" + j).indexOf("&"); colspan = Integer.valueOf(temp.substring(0, tempInt)); rowspan = Integer.valueOf(temp.substring(tempInt + 1)); } if (rowspan > 1) { int temp = rowspan; for (int x = i + 1; x < i + temp; x++) { hssfRow = hssfSheet.getRow(x); if (hssfRow != null) { for (int y = 0; y < hssfRow.getLastCellNum(); y++) { hssfCell = hssfRow.getCell(y); if (hssfCell != null) { hssfCell.setCellType(CellType.STRING); if (!"".equals(hssfCell.getStringCellValue())) { break; } else if (y == hssfRow.getLastCellNum() - 1) { rowspan--; } } } } } hssfRow = hssfSheet.getRow(i); hssfCell = hssfRow.getCell(j); } countcolpanNum[j] = colspan; } } } } } poifsFileSystem.close(); } catch (IOException e) { e.printStackTrace(); } }
第一次寫文章有點小緊張,而且懶得寫註釋了0.0.