使用 EasyPoi 完成复杂一对多 excel 表格导出功能

点击关注公众号,利用碎片时间学习


业务需求

从一个简单的仓库业务说起,仓库业务,会有进库记录,会有出库记录,会有库存,客户的需求就是需要一个库存盘点单,盘点单通俗来讲:将库存中每个商品的出入库记录都统计出来,看看每个商品出过多少货物,入过多少货物,本月库存多少,上月库存多少。

需求难点

一个货物会出过多次货物,入过多次货物,导出的 excel 就要做成 一对多 格式的导出

简单举例:

啤酒:入库2次,出库3次,最终体现在 excel 中效果如下图:

使用 EasyPoi 完成复杂一对多 excel 表格导出功能

通过 EasyPoi 实现需求

EasyPoi 文档地址:

http://doc.wupaas.com/docs/easypoi/easypoi-1c0u4mo8p4ro8

SpringBoot 使用:

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>4.2.0</version>
</dependency>

Gradle 使用:

implementation 'cn.afterturn:easypoi-base:4.2.0'
implementation 'cn.afterturn:easypoi-annotation:4.2.0'
implementation 'cn.afterturn:easypoi-web:4.2.0'

使用 EasyPoi 提供的注解,自定义导出类模板

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelIgnore;
import lombok.Getter;
import lombok.Setter;

import Java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 导出 excel 模板类
 */

@Getter
@Setter
public class ExportTemplate implements Serializable {
    @Excel(name = "序号", needMerge = true, type = 10)
    private int index;
    
    @Excel(name = "商品名称", needMerge = true, width = 30.0)
    private String goodName;
    
    @Excel(name = "商品单位", needMerge = true)
    private String goodUnit;
    
    @Excel(name = "上月库存数量", needMerge = true, type = 10)
    private Integer lastMonthSurplusNum;
    
    @Excel(name = "本月库存数量", needMerge = true, type = 10)
    private Integer thisMonthSurplusNum;
    
    @ExcelCollection(name = "本月入库信息")
    private List<GoodInItem> goodInItems;
    
    @ExcelCollection(name = "本月出库信息")
    private List<GoodOutItem> goodOutItems;
    
    @Excel(name = "备注", needMerge = true, width = 30.0)
    private String remark;

    /**
     * 入库信息
     */

    @Getter
    @Setter
    public static class GoodInItem {
        @Excel(name = "入库日期", exportFormat = "yyyy-MM-dd", width = 20.50)
        private Date purchaseDate;
        
        @Excel(name = "入库号", width = 25.50)
        private String purchaseNum;
        
        @Excel(name = "入库单价", type = 10)
        private BigDecimal unitPrice;
        
        @Excel(name = "入库数量", type = 10)
        private Integer totalNum;
    }

    /**
     * 出库信息
     */

    @Getter
    @Setter
    public static class GoodOutItem {
        @Excel(name = "出库日期", exportFormat = "yyyy-MM-dd", width = 20.50)
        private Date outDate;
        
        @Excel(name = "出库号", width = 25.50)
        private String sellNum;
        
        @Excel(name = "出库数量", type = 10)
        private Integer totalNum;
        
        @Excel(name = "成本金额", type = 10)
        private BigDecimal priceIn;
        
        @Excel(name = "销售金额", type = 10)
        private BigDecimal priceOut;
    }
}

实体类中使用的注解作用解释:

  • @Getter lombok 注解,用于给所有属性提供 getter 方法

  • @Setter lombok 注解,用于给所有属性提供 setter 方法

  • @Excel easypoi 注解,name 就等于导出 excel 的列名称,width 就是宽度,type 就是这个属性的类型,1表示文本,默认也是文本,10就是数字,needMerge 表示是否纵向合并单元格,也就是上下列合并

  • @ExcelCollection easypoi 注解,name 就等于导出 excel 的列名称,被此注解标注的集合,就等于在其列下面创建对等数量的行,就类似于这种

使用 EasyPoi 完成复杂一对多 excel 表格导出功能

最后模板弄好之后,就可以通过easypoi 的工具类来导出,easypoi 推荐的导出工具类如下:

使用 EasyPoi 完成复杂一对多 excel 表格导出功能

这个方法的三个参数表示含义解释:

  • ExportParams :参数表示Excel 导出参数设置类,easypoi 自定义的类
  • pojoClass:你要导出的类模板
  • dataSet:数据集合

具体实现

@GetMapping(value = "export")
public void export(HttpServletRequest req, HttpServletResponse resp) {
 List<ExportTemplate> exportData = new ArrayList();
 // 步骤1:构建要导出excel的数据集合
 for (int i = 0; i < 5; i++) {
  ExportTemplate data = new ExportTemplate();
        data.setIndex(i);
  data.setGoodName("测试商品");
  data.setGoodUnit("瓶");
  data.setLastMonthSurplusNum(5); // 上月库存
  data.setThisMonthSurplusNum(3); // 本月库存
  // ... 剩下的就是类似的加值
        exportData.add(data);
 }

 try {
  // 步骤2:开始导出 excel
  ExportParams params = new ExportParams();
  params.setTitle("库存盘点单标题");
  params.setSheetName("库存盘点单工作表名称");
  params.setType(ExcelType.XSSF);
  Workbook workbook = ExcelExportUtil.exportExcel(params, ExportTemplate.classexportData);
  
  String nowStr = DateTimeFormatter.ofPattern(LocalDateTime.now()).format("yyyyMMddHHmm"); // 时间串
  String fileName = nowStr + "_库存盘点单"// 文件名称
  String tempDir = "C:/Users/huxim/Downloads";
  File filePath = new File(tempDir + File.separator);
  if (!filePath.exists()) filePath.mkdirs(); // 如果文件目录不存在就创建这个目录

  FileOutputStream fos = new FileOutputStream(tempDir + File.separator + fileName);
  workbook.write(fos);
  fos.close();

  resp.setContentType("application/octet-stream");
  resp.setCharacterEncoding("utf-8");
  response.addHeader("Content-disposition""attachment; filename="
                    + this.makeDownloadFileName(req, fileName));
  IOUtils.copy(new FileInputStream(tempFile), response.getOutputStream());
  System.out.println("导出成功~~~");
 } catch (Exception e) {
  throw new RuntimeException("导出 excel 失败~~~");
 }
}

/**
 * 判断是否是 IE 浏览器
 * 返回对应的字符串格式
 */

public static String makeDownloadFileName(HttpServletRequest request, String fileName) {
 String agent = request.getHeader("User-Agent");
    byte[] bytes = fileName.getBytes(StandardCharsets.UTF_8);
    if (agent.contains("MSIE") || agent.contains("Trident") || agent.contains("Edge")) {
     // IE
        return new String(bytes, StandardCharsets.UTF_8);
 } else {
        return new String(bytes, StandardCharsets.ISO_8859_1);
 }
}

导出成功后的excel 就类似于如下这种:

使用 EasyPoi 完成复杂一对多 excel 表格导出功能

感谢阅读,希望对你有所帮助 :) 

来源:blog.csdn.net/qq_43647359/article/

details/117512165

推荐:

最全的java面试题库

使用 EasyPoi 完成复杂一对多 excel 表格导出功能
PS:因为公众号平台更改了推送规则,如果不想错过内容,记得读完点一下“在看”,加个“星标”,这样每次新文章推送才会第一时间出现在你的订阅列表里。“在看”支持我们吧!

原文始发于微信公众号(Java笔记虾):使用 EasyPoi 完成复杂一对多 excel 表格导出功能

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/59768.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!