Java – Excel读取多行数据
我需要读取超过300行的excel文件。 我只需要从特定的单元格中提取值。
码
Workbook workbook = Workbook.getWorkbook(new File(excelFile)); Sheet sheet = workbook.getSheet(0); Cell emp_name = sheet.getCell(1,2); Cell emp_dpt = sheet.getCell(2,2); Cell emp_pdpt = sheet.getCell(3,2); Cell emp_no = sheet.getCell(4,2); Cell emp_desn = sheet.getCell(5,2); Cell emp_dj = sheet.getCell(6,2); Cell emp_lvl = sheet.getCell(7,2); Cell emp_eval = sheet.getCell(8,2); String name = emp_name.getContents(); String dpartment = emp_dpt.getContents(); String pre_department = emp_pdpt.getContents(); String employee_no = emp_no.getContents(); String designation = emp_desn.getContents(); String datejoined = emp_dj.getContents(); String evalution = emp_eval.getContents(); System.out.println(name); System.out.println(dpartment); System.out.println(pre_department); System.out.println(employee_no); System.out.println(designation); System.out.println(datejoined); System.out.println(evalution);
上面的代码可以帮助我从Excel中获取数据,但只有一个值被提取。 我如何从Excel中获取所有数据。
做一个循环
当你说,sheet.getCell(1,2),你阅读第1列和第2行的单元格。
支持,如果你想读,列1和行3,然后做这sheet.getCell(1,3);
sheet.getRows() – >返回此表中的行数
伪代码:
for (int rowNum = 5; rowNum < sheet.getRows(); rowNum++) { int column = 4; sheet.getCell(column ++, rowNum).getContents(); //read 4th column and 5th row into a variable or object as per your logic; sheet.getCell(column ++, rowNum).getContents(); //read 5th column and 5th row; ...... }
你可以使用iterator
,它允许你读取每个单元格
看到这里的例子
Iterator<Row> rowIterator = sheet.iterator(); while(rowIterator.hasNext()) { Row row = rowIterator.next(); //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_BOOLEAN: System.out.print(cell.getBooleanCellValue() + "\t\t"); break; case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "\t\t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t\t"); break; } }