SpringBoot 使用 jxls 实现 excel 自由导出

830 阅读1分钟

springboot使用jxls模板动态导出excel

jxls官网参考地址:

1、导入pom

          <!-- jxls poi -->
          <dependency>
              <groupId>org.jxls</groupId>
              <artifactId>jxls-poi</artifactId>
              <version>2.10.0</version>
          </dependency>
          <dependency>
              <groupId>org.jxls</groupId>
              <artifactId>jxls</artifactId>
              <version>2.10.0</version>
          </dependency>
          <dependency>
              <groupId>net.sf.jxls</groupId>
              <artifactId>jxls-core</artifactId>
              <version>1.0.6</version>
          </dependency><!-- poi的版本要大于等于4.0.1,否则动态导出会有格式错误 -->
          <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi-ooxml</artifactId>
              <version>4.0.1</version>
          </dependency>
          <dependency>
              <groupId>org.apache.poi</groupId>
              <artifactId>poi</artifactId>
              <version>4.0.1</version>
          </dependency>

2、制定导出模板

1662446209960.png

1662446253261.png 编辑批注确定数据边界:

jx:each(items="list" var="list" lastCell="M5")

jx:area(lastCell="M5")

3、根据模板格式确定实体类结构

  import java.util.List;
  ​
  /**
   * @Author: x
   * @Date: 2022/6/6 06:06
   * @Description: 用于导出模板
   */
  public class ExportTemplate {
  ​
      private String fileName;
      private String stepName;
      private List<PlateDetail> list;
      ...
  ​
      //setter/getter方法
      
  ​
      public static class PlateDetail{
          private ExtCellData _a_1;
          private ExtCellData _a_2;
          private ExtCellData _a_3;
          private ExtCellData _a_4;
          private ExtCellData _a_5;
          private ExtCellData _a_6;
          private ExtCellData _a_7;
          private ExtCellData _a_8;
          private ExtCellData _a_9;
          private ExtCellData _a_10;
          private ExtCellData _a_11;
          private ExtCellData _a_12;
  ​
          //setter/getter方法
      }
  ​
  ​
      public static class ExtCellData{
  ​
          private String personName;
          ...
          
          //setter/getter方法
          
      }
  }

4、生成excel

      /**
       * 导出
       * @param id
       * @return
       */
      @GetMapping("/export/{id}")
      public void export(@PathVariable("id") Integer id,
                                            HttpServletRequest request,
                                            HttpServletResponse response){
          OutputStream os = null;
          InputStream is = null;
          try{
              //jsonObject:详情
              JSONObject jsonObject = new JSONObject();
              //将详情填充到模板实体类
              ExportTemplate exportTemplate = poiMouduleService.buildExportTemplate(jsonObject);
  ​
              //读取模板
              is = this.getClass().getClassLoader().getResourceAsStream(TemplateConstant.EXPORE_MODULE);
  ​
              //实体类转换为map
              Map<String,Object> map = BeanUtil.transBean2Map(exportTemplate);
                  
              Context context = new Context(map);
  ​
              os = getOutputStream(exportTemplate.getFileName(),request,response);
  ​
              JxlsHelper.getInstance().processTemplate(is, os, context);
  ​
              os.flush();
          }catch (Exception e){
              e.printStackTrace();
          }finally {
  ​
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              try {
                  os.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
  ​
      private static OutputStream getOutputStream(String fileName,
                                                  HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
          try {
              
  ​
              String userAgent = request.getHeader("USER-AGENT");
              fileName = fileName + ".xlsx";
              // 设置response的Header
              if (userAgent != null) {
                  String lowuserAgent = userAgent.toLowerCase();
                  if (lowuserAgent.contains("windows")) {
                      //windows
                      response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                  } else  {
                      //非windows
                      response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1"));
  ​
                  }
              } else {
                  //windows
                  response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
              }
             
              response.setContentType("application/vnd.ms-excel;charset=utf-8");
              response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
  ​
              return response.getOutputStream();
          } catch (IOException e) {
              throw new Exception("导出excel表格失败!", e);
          }
      }

备注:

如果导出excel名称中包含中文。使用postman测试时,中文不会被解析,仍按编码格式导出。浏览器会识别编码格式,自动解析成中文。