easyexcel导出多个sheet Java示例
时间: 2023-07-29 20:08:07 浏览: 126
好的,下面是一个使用 EasyExcel 导出多个sheet 的 Java 示例代码:
```java
public void exportExcelWithMultipleSheets(HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("多个Sheet的Excel文件", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
OutputStream outputStream = response.getOutputStream();
ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
// 写入第一个Sheet
WriteSheet sheet1 = EasyExcel.writerSheet(0, "Sheet1").head(Student.class).build();
List<Student> students1 = getStudents1(); // 获取第一个Sheet的数据
excelWriter.write(students1, sheet1);
// 写入第二个Sheet
WriteSheet sheet2 = EasyExcel.writerSheet(1, "Sheet2").head(Teacher.class).build();
List<Teacher> teachers = getTeachers(); // 获取第二个Sheet的数据
excelWriter.write(teachers, sheet2);
// 关闭ExcelWriter
excelWriter.finish();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private List<Student> getStudents1() {
// 获取第一个Sheet的数据
// ...
}
private List<Teacher> getTeachers() {
// 获取第二个Sheet的数据
// ...
}
```
代码中首先设置了响应头,然后创建一个 ExcelWriter 实例。接着分别创建了两个 WriteSheet 实例,分别用于写入两个 Sheet 的数据。最后通过 ExcelWriter 将数据写入 Excel 文件,并关闭 ExcelWriter。
阅读全文