xiaoming728

xiaoming728

EasyPoi动态表头导入

2024-04-07
EasyPoi动态表头导入

独特的功能

  • 基于注解的导入导出,修改注解就可以修改Excel

  • 支持常用的样式自定义

  • 基于map可以灵活定义的表头字段

  • 支持一堆多的导出,导入

  • 支持模板的导出,一些常见的标签,自定义标签

  • 支持HTML/Excel转换,如果模板还不能满足用户的变态需求,请用这个功能

  • 支持word的导出,支持图片,Excel

引入pom.xml

<!-- EasyPoi -->
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-spring-boot-starter</artifactId>
    <version>4.4.0</version>
</dependency>

代码编写

根据不同Excel格式读取数据

try {
    if (file.getOriginalFilename().endsWith(".xls") || file.getOriginalFilename().endsWith(".xlsx") ||
            file.getOriginalFilename().endsWith(".XLS") || file.getOriginalFilename().endsWith(".XLSX")) {
        // 如果是xls、xlsx使用ExcelImportUtil.importExcel方法
        ImportParams params = new ImportParams();
        params.setTitleRows(template.getTitleLine());
        params.setHeadRows(template.getDataLine());
        // 获取excel sheet数量
        Workbook hssfWorkbook = WorkbookFactory.create(file.getInputStream());
        params.setSheetNum(hssfWorkbook.getNumberOfSheets());
        data = ExcelImportUtil.importExcel(file.getInputStream(), Map.class, params);
    } else if (file.getOriginalFilename().endsWith(".csv") || file.getOriginalFilename().endsWith(".CSV")   ) {
        // 如果是csv使用CsvImportUtil.importCsv方法
        CsvImportParams csvImportParams = new CsvImportParams();
        csvImportParams.setTitleRows(template.getTitleLine());
        csvImportParams.setHeadRows(template.getDataLine());
        data = CsvImportUtil.importCsv(file.getInputStream(), Map.class, csvImportParams);
    } else {
        throw new ServiceException("文件格式错误");
    }
} catch (Exception e) {
    e.printStackTrace();
    throw new ServiceException("文件格式错误");
}

获取动态表头

// 根据template获取表头信息再解析数据
List<ExcelExportEntity> entityList = new ArrayList<>();
List<JSONObject> templateJsonArray = JSON.parseArray(template.getJson(), JSONObject.class);
// templateJsonArray结构 [{"fieldName":"store","fieldValue":"门店名称","templateTitle":"业务机构名称"}]
for (JSONObject entries : templateJsonArray) {
    entityList.add(new ExcelExportEntity(entries.get("templateTitle").toString(), entries.get("fieldName")));
}

根据表头解析数据

for (Map<String, Object> map : data) {
    JSONObject jsonObject = new JSONObject();
    JSONObject nameJson = new JSONObject();
    for (ExcelExportEntity entity : entityList) {
        jsonObject.put(entity.getKey().toString(), map.get(entity.getName()));
        nameJson.put(entity.getKey().toString(), entity.getName());
    } 
...