1、导EasyExcel依赖
<groupId>com.alibabagroupId>
<artifactId>easyexcelartifactId>
2、创建导出excel的实体类
@HeadStyle(fillForegroundColor = 9)
@HeadFontStyle(fontHeightInPoints = 12, bold = BooleanEnum.TRUE)
@ContentStyle(horizontalAlignment = HorizontalAlignmentEnum.CENTER, verticalAlignment = VerticalAlignmentEnum.CENTER,borderTop = BorderStyleEnum.THIN,borderBottom = BorderStyleEnum.THIN,borderLeft = BorderStyleEnum.THIN,borderRight = BorderStyleEnum.THIN)
@ContentFontStyle(fontHeightInPoints = 11)
@ExcelProperty(value = "序号", index = 0)
@ExcelProperty(value = "姓名", index = 1)
@ExcelProperty(value = "时间", index = 2)
@ExcelProperty(value = "备注", index = 3)
@ExcelProperty(value = "图片", index = 4)
@ContentStyle(shrinkToFit = BooleanEnum.TRUE,borderTop = BorderStyleEnum.THIN,borderBottom = BorderStyleEnum.THIN,borderLeft = BorderStyleEnum.THIN,borderRight = BorderStyleEnum.THIN)
3、代码进行逻辑赋值
controller
@GetMapping(value = "/exportExcel")
public void exportExcel(HttpServletResponse response, HttpServletRequest request,T entity) {
jsjtProblemLabelService.exportExcel(response, request,entity);
service
public void exportExcel(HttpServletResponse response, HttpServletRequest request,T entity) {
List list = ListUtils.newArrayList();
List excelListBySQL = new ArrayList();
for (int i = 0; i < excelListBySQL.size(); i++) {
Excel excel = excelListBySQL.get(i);
ExcelDto excelDto = new ExcelDto();
excelDto.setNumber(String.valueOf(++number));
excelDto.setName(excel .getName());
excelDto.setTime(excel .getTime());
excelDto.setText(excel .getText());
excelDto.setImage(imageByUrl(excel .getImageUrl()));
String fileName = URLEncoder.encode("EasyExcel导出.xlsx", "UTF-8");
OutputStream fileOutputStream = null;
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
fileOutputStream = response.getOutputStream();
ExcelWriter excelWriter = EasyExcel.write(fileOutputStream, ExcelDto.class)
WriteSheet sheet = EasyExcel.writerSheet(0, "sheet1").build();
excelWriter.write(list, sheet);
fileOutputStream.flush();
fileOutputStream.close();
public File imageByUrl(String imageUrl) throws Exception{
if (StringUtils.isBlank(imageUrl)){
URI uri = new URI("file:///" + path+"/"+imageUrl);
File file = new File(uri);
return file.exists() ? file : null;