1.依赖
<!-- 导出excel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
2.格式注解
@Data
public class userExcel {
@ExcelProperty("用户名称")
@ColumnWidth(20)
private String username;
@ExcelProperty("姓名")
@ColumnWidth(20)
private String name;
@ExcelProperty("密码")
@ColumnWidth(20)
private String password;
}
3.代码
@GetMapping
public void export(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "ids",required = false) List<String> ids) throws IOException {
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
if (CollectionUtils.isNotEmpty(ids)) {
queryWrapper.in(Employee::getId, ids);
}
List<Employee> list = employeeMapper.selectList(queryWrapper);
List<userExcel> resList = new ArrayList<>();
for (Employee employee : list) {
userExcel userExcel = new userExcel();
BeanUtils.copyProperties(employee, userExcel);
resList.add(userExcel);
}
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");
String filename = URLEncoder.encode("表名称", "UTF-8");
response.setHeader("Content-disposition", String.format("attachment;filename=%s.xlsx",filename));
EasyExcel.write(response.getOutputStream(), userExcel.class)
.sheet("Sheet1")
.doWrite(resList);
}