该错误是由于使用HSSFWorkbook 操作Excel2007引起的。
解决方法如下:
使用HSSFWorkbook操作Excel2003,
使用XSSFWorkbook操作Excel2007。
操作Excel2007所需依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
代码示例:
@SneakyThrows
public static void main(String[] args) throws IOException {
List<User> userList = new ArrayList<>();
// 创建10个user对象
for (long i = 0; i < 10; i++) {
User user = new User(i, "用户" + i, "武汉" + i, new Date());
userList.add(user);
}
XSSFWorkbook workbook = null;
try {
// 导入模板
workbook = new XSSFWorkbook(new File("D:\\excel.xlsx"));
} catch (IOException e) {
e.printStackTrace();
}
// 获取模板中的第一张 sheet表格
XSSFSheet sheet = workbook.getSheetAt(0);
// 从第3行开始插入数据
int row=2;
for (User user : userList) {
// 获取 该行数据
XSSFRow sheetRow = sheet.getRow(row);
// 获取 第一个单元格
XSSFCell cell1 = sheetRow.getCell(0);
// 给第一个单元格赋值 id
cell1.setCellValue(user.getId()+1);
// 获取 第二个单元格
XSSFCell cell2 = sheetRow.getCell(1);
// 给第一个单元格赋值 name
cell2.setCellValue(user.getName());
// 获取 第三个单元格
XSSFCell cell3 = sheetRow.getCell(2);
// 给第三个单元格赋值 address
cell3.setCellValue(user.getAddress());
// 获取 第四个单元格
XSSFCell cell4 = sheetRow.getCell(3);
// 给第四个单元格赋值 birth
// 设置时间格式
String date = DateUtil.format(user.getBirth(), "yyyy-MM-dd");
cell4.setCellValue(date);
// 开始下一行
row++;
}
// 将数据填充到执行文件中
workbook.write(new FileOutputStream(new File("D://temp.xlsx")));
System.out.println("填充结束");
}