一,controller层:
public void exportCollect(@RequestBody List<AcquisitionRecord> acquisitionRecordList, HttpServletResponse response) {
acquisitionRecordService.exportCollect(acquisitionRecordList, response);
}
acquisitionRecordList //前端传的数据可以是实体集合,也可以是id集合 response //响应头
二,serviceimpl层
@Override
public void exportCollect(List<AcquisitionRecord> acquisitionRecordList, HttpServletResponse response) {
String fileName = "采集统计" + UUID.randomUUID().toString() + ".xlsx";
List<ExportCollectionDto> exportCollectionDtos = ConvertUtils.sourceToTarget(acquisitionRecordList, ExportCollectionDto.class);
// 设置返回的文件类型为Excel文件
response.setContentType("application/vnd.ms-excel");
// response.setCharacterEncoding("utf-8");
// 设置返回的文件名
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 使用try-with-resources自动关闭流
try (OutputStream out = response.getOutputStream()) {
// 将Excel文件内容写入输出流中
EasyExcel.write(out, ExportCollectionDto.class)
.sheet("模板")
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.doWrite(exportCollectionDtos);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
String fileName = “采集统计” + UUID.randomUUID().toString() + “.xlsx”; //设置下载文件名
三,xlsx模板DTO
@Data
public class ExportCollectionDto {
/**
* 姓名
*/
@ExcelProperty("姓名")
private String username;
/**
* 编号
*/
@ExcelProperty("编号")
private String userId;
/**
* 采集次数
*/
@ExcelProperty("采集次数")
private Integer acquisitionFrequency;
}
返回表头为 姓名 编号 采集次数 的表格