在 pom.xml 中添加依赖项 -
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
Excel 2007 或更高版本 (.xlsx) - 示例代码 -
//reading data from byte array
OPCPackage pkg = OPCPackage.open(new ByteArrayInputStream(data));
Workbook wb = new XSSFWorkbook(pkg);
Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
int j = 5;
Person person= new Person ();
Row row = rows.next();
if (row.getRowNum() > 0) {
person.setPersonId((int)(row.getCell(0).getNumericCellValue()));
person.setFirstName(row.getCell(1).getStringCellValue());
person.setLastName(row.getCell(2).getStringCellValue());
person.setGroupId((int)(row.getCell(3).getNumericCellValue()));
person.setUserName(row.getCell(4).getStringCellValue());
person.setCreditId((int)(row.getCell(5).getNumericCellValue()));
}
}
2)
//reading from a file
File file = new File(pathxlsx);
FileInputStream fis = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
int j = 5;
Person person= new Person ();
Row row = rows.next();
if (row.getRowNum() > 0) {
person.setPersonId((int)(row.getCell(0).getNumericCellValue()));
person.setFirstName(row.getCell(1).getStringCellValue());
person.setLastName(row.getCell(2).getStringCellValue());
person.setGroupId((int)(row.getCell(3).getNumericCellValue()));
person.setUserName(row.getCell(4).getStringCellValue());
person.setCreditId((int)(row.getCell(5).getNumericCellValue()));
}
}
Excel 1998-2003 文件 (.xls) - 您可以使用 HSSF 库。只需使用:Workbook wb = new HSSFWorkbook(pkg);