获取Excel中的列号

在我的Java应用程序中,我试图使用apache-poi将excel转换为pdf。在我的excel文件中,某些行的列数是不同的。第一行和第二行包含一列,其余行包含8列。这里是我的代码

while (rowIterator.hasNext()) { Row row = rowIterator.next(); int cellNumber = 0; if (flag) { table = new PdfPTable(row.getLastCellNum()); flag = false; } // For each row, iterate through each columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (temp == 0) { numberOfColumns = row.getLastCellNum(); PdfPCell c1 = new PdfPCell(new Phrase( cell.getStringCellValue())); c1.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c1); table.setHeaderRows(1); }else{ cellNumber =checkEmptyCellAndAddCellContentToPDFTable(cellNumber,cell,table); } cellNumber++; break; case Cell.CELL_TYPE_NUMERIC: cellNumber =checkEmptyCellAndAddCellContentToPDFTable(cellNumber,cell,table); cellNumber++; break; } } temp = 1; if(numberOfColumns != cellNumber){ for(int i=0;i<(numberOfColumns-cellNumber);i++){ table.addCell(" "); } } 

}

所以当我执行这个时,我会得到只有一列的pdf文件。但是我想和我的excel格式一样。我怎样才能在我的代码dynamic实现这一点(我也必须应用这种逻辑的其他Excel文件也)?

你可以使用这种方法迭代每一行的每个单元格。

  Sheet sheet = workbook.getSheetAt(0); //Iterate through each rows from first sheet Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); if(isRowEmpty(row)){ System.out.println("Row "+row.getRowNum()+"is a empty row"); continue; } Iterator<Cell> cellIterator = row.cellIterator(); Cell cell =null; while (cellIterator.hasNext()) { cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: String value = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: Double d = cell.getNumericCellValue(); break; case Cell.CELL_TYPE_STRING: String value = cell.getStringCellValue().trim(); break; case Cell.CELL_TYPE_BLANK: break; } } }