当前poi的版本为
<poi.veriosn>4.1.2</poi.veriosn>
相关依赖
<!-- apache POI for xls -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.veriosn}</version>
</dependency>
<!-- apache POI for xlsx -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.veriosn}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.veriosn}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.veriosn}</version>
</dependency>
案例代码
public static void main(String[] args) throws IOException {
String fileName = "D:\\data\\excel\\workbook.xls";
File file = new File(fileName);
if (file.exists()) {
FileUtils.forceDelete(file);
}
// 首先创建一个空的excel
try (Workbook wb = WorkbookFactory.create(false)) {
Sheet wbSheet = wb.createSheet();
Row row = wbSheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("First Row");
try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
}
}
for (int i = 0; i < 10; i++) {
// 根据指定的流创建excel
try (Workbook wb = WorkbookFactory.create(new FileInputStream(fileName))) {
Sheet wbSheet = wb.getSheetAt(0);
Row row = wbSheet.createRow(i + 1);
Cell cell = row.createCell(i);
cell.setCellValue("Hello World!" + i);
try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
}
}
}
}
结果如下所示(后面的Hello World都是通过追加的方式添加的)