【笔记】SpringBoot项目通过EasyExcel返回Excel文件给前端

前言

SpringBoot项目通过EasyExcel返回Excel文件给前端

添加依赖

pom.xml
1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>

固定表头

定义实体类

@ExcelProperty(""):定义表头

value = "":定义表头
index = 0:定义表头索引,默认按照属性定义顺序作为表头顺序

@ColumnWidth(40):定义列宽度

1
2
3
4
5
6
7
8
9
10
@Data
public class UserExcelDTO {

@ExcelProperty("第一列")
private String first;

@ExcelProperty("第二列")
private String last;

}

添加数据

1
2
3
4
5
6
7
8
9
10
11
@Service
public class UserService {

public List<UserExcelDTO> exportUser() {
List<UserExcelDTO> list = new ArrayList<>();
list.add(new UserExcelDTO("第一行第一列值", "第一行第二列值"));
list.add(new UserExcelDTO("第二行第一列值", "第二行第二列值"));
return list;
}

}

返回Excel文件给前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RestController
public class UserController {

@Autowired
private UserService userService;

@GetMapping("/exportUser")
public void exportUser(HttpServletResponse response) {
// 查询数据
List<UserExcelDTO> data = userService.exportUser();

// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
String fileName = URLEncoder.encode("文件名", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

// 返回数据
EasyExcel.write(response.getOutputStream(), UserExcelDTO.class)
.sheet("表名")
.doWrite(data);
}

}

动态表头

定义实体类

1
2
3
4
5
6
7
8
9
@Data
@AllArgsConstructor
public class ExcelDTO {

private List<List<String>> head;

private List<List<Object>> data;

}

添加表头和数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Service
public class UserService {

public ExcelDTO exportUser() {
// 添加表头
List<List<String>> head = new ArrayList();
head.add(Arrays.asList("第一列", "第二列"));

// 添加数据
List<List<Object>> data = new ArrayList();
data.add(Arrays.asList("第一行第一列值", "第一行第二列值"));
data.add(Arrays.asList("第二行第一列值", "第二行第二列值"));

// 返回表头和数据
return new ExcelDTO(head, data);
}

}

返回Excel文件给前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@RestController
public class UserController {

@Autowired
private UserService userService;

@GetMapping("/exportUser")
public void exportUser(HttpServletResponse response) {
// 查询数据
ExcelDTO excelDTO = userService.exportUser();

// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
String fileName = URLEncoder.encode("文件名", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

// 返回数据
EasyExcel.write(response.getOutputStream())
.head(excelDTO.head)
.sheet("表名")
.doWrite(excelDTO.data);
}

}

完成