SpringBoot使用esayExcel根据模板导出excel

1、依赖

java 复制代码
       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.1.3</version>
        </dependency>

2、模板

3、实体类

java 复制代码
package com.skybird.iot.addons.productionManagement.qualityTesting.backend.jdo;

import com.alibaba.excel.annotation.ExcelProperty;

public class qualityTestingExcelDao {

  @ExcelProperty("序号")
  private String index;

  @ExcelProperty("质检类别")
  private String workingProcedure;

  @ExcelProperty("检查部位")
  private String inspectionPart;

  @ExcelProperty("检查内容")
  private String inspectionContent;

  @ExcelProperty("检查方法")
  private String inspectionMethod;

  @ExcelProperty("检查结果")
  private String inspectionResult;

  @ExcelProperty("备注")
  private String notes;

  public String getIndex() {
    return index;
  }

  public void setIndex(String index) {
    this.index = index;
  }

  public String getWorkingProcedure() {
    return workingProcedure;
  }

  public void setWorkingProcedure(String workingProcedure) {
    this.workingProcedure = workingProcedure;
  }

  public String getInspectionPart() {
    return inspectionPart;
  }

  public void setInspectionPart(String inspectionPart) {
    this.inspectionPart = inspectionPart;
  }

  public String getInspectionContent() {
    return inspectionContent;
  }

  public void setInspectionContent(String inspectionContent) {
    this.inspectionContent = inspectionContent;
  }

  public String getInspectionMethod() {
    return inspectionMethod;
  }

  public void setInspectionMethod(String inspectionMethod) {
    this.inspectionMethod = inspectionMethod;
  }

  public String getInspectionResult() {
    return inspectionResult;
  }

  public void setInspectionResult(String inspectionResult) {
    this.inspectionResult = inspectionResult;
  }

  public String getNotes() {
    return notes;
  }

  public void setNotes(String notes) {
    this.notes = notes;
  }

  @Override
  public String toString() {
    return "qualityTestingExcelDao{"
        + "index='"
        + index
        + '\''
        + ", workingProcedure='"
        + workingProcedure
        + '\''
        + ", inspectionPart='"
        + inspectionPart
        + '\''
        + ", inspectionContent='"
        + inspectionContent
        + '\''
        + ", inspectionMethod='"
        + inspectionMethod
        + '\''
        + ", inspectionResult='"
        + inspectionResult
        + '\''
        + ", notes='"
        + notes
        + '\''
        + '}';
  }
}

4、接口

java 复制代码
private static List<qualityTestingExcelDao> getList(Document dto) {
    List<Document> list = DocuLib.getList(dto, "qualityInspectionList");
    List<qualityTestingExcelDao> excelList = new ArrayList<>();
    // 用于记录当前质检序号
    int index = 0;
    // 用于记录当前质检类别
    String inspectionPart = "";
    for (int i = 0; i < list.size(); i++) {
      Document item = list.get(i);
      String workingProcedure = DocuLib.getStr(item, "workingProcedure");
      List<Document> detectionList = DocuLib.getList(item, "detectionList");
      if (ObjectUtils.isNotEmpty(detectionList)) {
        for (Document row : detectionList) {
          qualityTestingExcelDao dao = new qualityTestingExcelDao();
          String inspectionPartDb = DocuLib.getStr(row, "project");
          if (!inspectionPart.equals(inspectionPartDb)) {
            inspectionPart = inspectionPartDb;
            index++;
          }
          dao.setIndex(String.valueOf(index));
          dao.setWorkingProcedure(workingProcedure);
          dao.setInspectionPart(inspectionPartDb);
          dao.setInspectionContent(DocuLib.getStr(row, "content"));
          dao.setInspectionMethod(DocuLib.getStr(row, "inspectionMethods.name"));
          dao.setInspectionResult(DocuLib.getStr(row, "result.name"));
          dao.setNotes(DocuLib.getStr(row, "illustrate"));
          excelList.add(dao);
        }
      } else {
        qualityTestingExcelDao dao = new qualityTestingExcelDao();
        dao.setIndex(String.valueOf(index));
        dao.setWorkingProcedure(workingProcedure);
        excelList.add(dao);
      }
    }
    return excelList;
  }

  /**
   * 根据模板下载
   *
   * @param response
   * @throws IOException
   */
  @GetMapping("/excel")
  public void excel(HttpServletResponse response, @RequestParam("id") String id)
      throws IOException {
    try {
      Document dto = DBUtils.find(qualityTesting.collectionName, new Document("id", id));
      List<qualityTestingExcelDao> excelList = getList(dto);

      InputStream templateStream =
          qualityTestingWeb.class.getResourceAsStream("/templates/qualityTesting.xlsx");
      if (templateStream == null) {
        throw new FileNotFoundException("未找到模板文件");
      }
      // 生成目标文件
      ExcelWriter excelWriter =
          EasyExcel.write(response.getOutputStream()).withTemplate(templateStream).build();
      WriteSheet writeSheet = EasyExcel.writerSheet().build();
      // 每次都会重新生成新的一行,而不是使用下面的空行
      FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
      // 替换第一种占位符
      Map<String, Object> map = new HashMap<>();
      map.put("name", DocuLib.getStr(dto, "productName"));
      map.put("userName", DocuLib.getStr(dto, "completeBy.name"));
      map.put("time", DocuLib.getStr(dto, "completeDate"));
      excelWriter.fill(map, writeSheet);
      // 第二种占位符替换,这里定义了 hisData
      excelWriter.fill(new FillWrapper("dto", excelList), fillConfig, writeSheet);
      excelWriter.finish();
      // 设置响应头
      response.setContentType("application/vnd.ms-excel"); // 设置文本内省
      response.setCharacterEncoding("utf-8"); // 设置字符编码
      response.setHeader("Content-disposition", "attachment;fileName=name.xlsx");
      // 关闭模板流
      templateStream.close();
    } catch (FileNotFoundException e) {
      // 处理文件未找到异常
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);
      // 返回适当的错误消息
      response.getWriter().write("未找到模板文件");
    } catch (Exception e) {
      // 处理其他异常
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      // 返回适当的错误消息
      response.getWriter().write("内部服务器错误");
    }
  }

5、效果

相关推荐
阿乾之铭1 分钟前
Spring Boot框架中的IO
java·spring boot·log4j·1024程序员节
有梦想的咕噜6 分钟前
Electron 是一个用于构建跨平台桌面应用程序的开源框架
前端·javascript·electron
程序猿阿伟7 分钟前
《C++中的魔法:实现类似 Python 的装饰器模式》
java·c++·装饰器模式
yqcoder8 分钟前
electron 监听窗口高端变化
前端·javascript·vue.js
Mr. zhihao9 分钟前
装饰器模式详解:动态扩展对象功能的优雅解决方案
java·开发语言·装饰器模式
2401_8576009516 分钟前
商场应急管理:SpringBoot技术解决方案
java·spring boot·后端
Python私教24 分钟前
Flutter主题最佳实践
前端·javascript·flutter
想做白天梦28 分钟前
多级反馈队列
java·windows·算法
潇雷30 分钟前
算法Day12|226-翻转二叉树;101-对称二叉树;104-二叉树最大深度;111-二叉树最小深度
java·算法·leetcode