Java若依框架导出excel自定义导出多个sheet
时间: 2023-09-29 08:11:17 浏览: 149
java导出包含多个sheet的Excel代码示例
1. 在pom.xml中添加poi和poi-ooxml的依赖:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 创建Workbook和Sheet对象,并设置表头和数据:
```java
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
Sheet sheet2 = workbook.createSheet("Sheet2");
//设置表头
Row row1 = sheet1.createRow(0);
row1.createCell(0).setCellValue("姓名");
row1.createCell(1).setCellValue("年龄");
Row row2 = sheet2.createRow(0);
row2.createCell(0).setCellValue("学科");
row2.createCell(1).setCellValue("成绩");
//设置数据
Row row3 = sheet1.createRow(1);
row3.createCell(0).setCellValue("张三");
row3.createCell(1).setCellValue(20);
Row row4 = sheet2.createRow(1);
row4.createCell(0).setCellValue("语文");
row4.createCell(1).setCellValue(80);
```
3. 将Workbook对象写入输出流:
```java
response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
```
完整代码:
```java
@RequestMapping("/export")
public String export(HttpServletResponse response) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
Sheet sheet2 = workbook.createSheet("Sheet2");
//设置表头
Row row1 = sheet1.createRow(0);
row1.createCell(0).setCellValue("姓名");
row1.createCell(1).setCellValue("年龄");
Row row2 = sheet2.createRow(0);
row2.createCell(0).setCellValue("学科");
row2.createCell(1).setCellValue("成绩");
//设置数据
Row row3 = sheet1.createRow(1);
row3.createCell(0).setCellValue("张三");
row3.createCell(1).setCellValue(20);
Row row4 = sheet2.createRow(1);
row4.createCell(0).setCellValue("语文");
row4.createCell(1).setCellValue(80);
response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
return "success";
}
```
阅读全文