每次只读一行/只有特定的列和创build对象
我使用Apache poi导入我在桌面区域中的.xlsx文件。
通过下面的代码,我可以阅读我想要的孔表。
但是我想每次只读一行,每行只读特定的列(例如,我只想从第一行开始将列A,F和G保存为对象,然后对于第二行,第三行等)
我该怎么做?
public class main { public static void main( String[] args ) throws Exception { InputStream ExcelFileToRead = new FileInputStream("C:/User/Desktop/test.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFSheet sheet=wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { row=(XSSFRow) rows.next(); Iterator cells = row.cellIterator(); while (cells.hasNext()) { cell=(XSSFCell) cells.next(); if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { System.out.print(cell.getStringCellValue()+" "); } else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { System.out.print(cell.getNumericCellValue()+" "); } else { } } System.out.println(); } } }
可以使用从Sheet
对象检索特定的行
Sheet.getRow(index)
其中index
是基于零的行号。 也就是说,要读取第1行,必须得到索引为零的行,第2行在索引为1,依此类推。 同样,可以使用Row
对象从中检索特定的单元格
Row.getCell(index)
索引再次是基于零的单元格编号,其中单元格列A位于索引0,列B位于索引1,依此类推。 因此,要在B2中检索单元格,可以使用
Cell cell = Sheet.getRow(1).getCell(1);