使用POI导出Excel

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

最近有个需求需要导出Excel,要求使用POI,这里记录一下


一、导入依赖

首先在项目中导入POI需要的依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

二、使用步骤

1.编写工具类

因为导出Excel在项目中的多处地方都有使用,所以仅仅在一个地方去编写显然不符合代码复用的要求,私以为抽出一个工具类是最佳方案,工具类如下:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;


@Component
public class ExcelUtil {

    /**
     * 导出表格
     *
     * @param data
     * @param filePath
     */
    public void createExcel(List<List<String>> data, String filePath) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        for (int i = 0; i < data.size(); i++) {
            List<String> rowDate = data.get(i);
            Row row = sheet.createRow(i);
            for (int j = 0; j < rowDate.size(); j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(rowDate.get(j));
            }
        }
        File fileExcel = new File(filePath);
        fileExcel.deleteOnExit();
        File folder = new File(filePath.substring(0, filePath.indexOf(File.separator)));
        if (!folder.exists()) {
            folder.mkdirs();
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
            workbook.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

工具类中编写了一个导出Excel的方法,核心思想是:将需要导出的数据传入,data是一个双层List集合,里边的每一个子集合都是需要导出的每一行的数据,第一行是表头,将集合中的每一行拿出创建excel的行,再输出到工作簿中。而filePath就是我们需要输出Excel的路径,其实也可以将方法改造成流的形式,让用户自己决定去保存到某个位置。但是,,,,产品的需求是生成的excel要上传到OSS云存储,然后前端会拿到一个地址,然后再执行下载,咱也不知道,就按照需求来吧。

2.传入数据

这里需要我们自己在业务层去将需要导出的数据进行整合。具体看下边代码

//根据查询条件查询场景记录
  List<SceneRecord> sceneRecordList = baseMapper.selectList(queryWrapper);
   List<List<String>> data = new ArrayList<>();
   List<String> headerData = new ArrayList<>(sceneRecordList.size());
   headerData.add("时间");
   headerData.add("会员ID");
   headerData.add("场景名称");
   headerData.add("减排量变化");
   headerData.add("附带信息");
   data.add(headerData);
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   //查询场景名称
   List<SceneRule> sceneRuleList = sceneRuleMapper.selectList(new QueryWrapper<>());
   HashMap<String, String> map = new HashMap<>(sceneRuleList.size());
   //遍历场景规则
   for (SceneRule rule : sceneRuleList) {
       map.put(rule.getId(), rule.getName());
   }
   for (SceneRecord sceneRecord : sceneRecordList) {
       List<String> bodyData = new ArrayList<>(sceneRecordList.size());
       bodyData.add(simpleDateFormat.format(sceneRecord.getCreateTime()));
       bodyData.add(sceneRecord.getMemberId());
       //将对应的场景名称添加
       bodyData.add(map.get(sceneRecord.getSceneRuleId()));
       bodyData.add(String.valueOf(sceneRecord.getEmission()));
       bodyData.add(sceneRecord.getAdditional());
       data.add(bodyData);
   }
   SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
   Date date = new Date();
   String filename = "场景减排量记录-" + simpleDateFormat1.format(date) + date.getTime() + ".xlsx";
   excelUtil.createExcel(data, BasicFilePath.PATH + File.separator + filename);
   String path = "";
   try {
       File file = new File(BasicFilePath.PATH + File.separator + filename);
       path = ossUtil.upload(filename, new FileInputStream(file));
       file.delete();
   } catch (FileNotFoundException e) {
       e.printStackTrace();
   }
   return ossUtil.getUrl(path);

其中部分业务代码,没有贴上去,应该可以看出个大概,主要操作就是先将header表头数据存入,然后将需要导出的数据一行行的添加进去,场景名称和场景规则这些是前端需要的数据处理,可以不用看,以上就是这次需求的解决办法


总结

另外一种EasyExcel之前已经记录过详情看这一篇博客
使用EasyExcel进行导入导出数据

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值