easyexcel导入/导出 合并相同列

项目引入easyexcel相关依赖

	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>easyexcel</artifactId>
		<version>3.3.3</version>
	</dependency>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
	</dependency>

controlelr层导出功能

    @GetMapping("export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 准备测试数据
        List<DemoDataVO> list = new ArrayList<>();
        list.add(new DemoDataVO("张三", "语文", "90"));
        list.add(new DemoDataVO("张三", "数学", "80"));
        list.add(new DemoDataVO("王五", "英语", "70"));
        list.add(new DemoDataVO("王五", "政治", "85"));
        list.add(new DemoDataVO("李四", "历史", "88"));
        list.add(new DemoDataVO("马六", "历史", "77"));
        
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        String fileName = "demo export"+ ".xlsx";
        fileName = new String(fileName.getBytes(), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
        EasyExcel.write(response.getOutputStream(), DemoDataVO.class)
                .registerWriteHandler(new MergeCellWriteHandler())
                .autoCloseStream(Boolean.FALSE)
                .sheet("demo")
                .doWrite(list);
    }

DemoDataVO类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class DemoDataVO {

    @ExcelProperty(value = "姓名", index = 0)
    private String name;

    @ExcelProperty(value = "学科", index = 1)
    private String subject;

    @ExcelProperty(value = "成绩", index = 2)
    private String score;

}

MergeCellWriteHandler类


public class MergeCellWriteHandler implements CellWriteHandler {


    private Map<Integer, String> lastContentMap = new HashMap<>();

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {

        CellWriteHandler.super.beforeCellCreate(writeSheetHolder, writeTableHolder, row, head, columnIndex, relativeRowIndex, isHead);
    }

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        int columnIndex = cell.getColumnIndex();
        String content = cellData.getStringValue();

        if (lastContentMap.containsKey(columnIndex) && lastContentMap.get(columnIndex).equals(content)) {
            mergeCells(writeSheetHolder, columnIndex, relativeRowIndex);
        }

        lastContentMap.put(columnIndex, content);
    }

    private void mergeCells(WriteSheetHolder writeSheetHolder, int columnIndex, Integer relativeRowIndex) {
        CellRangeAddress cellRangeAddress = new CellRangeAddress(relativeRowIndex, relativeRowIndex+1, columnIndex, columnIndex);
        Sheet sheet = writeSheetHolder.getSheet();
        sheet.addMergedRegion(cellRangeAddress);
    }
}

导出excel结果

导入功能和正常easyexcel的导入一样

    @PostMapping("/import")
    public void importCustomer(@RequestParam(value = "file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        List<DemoDataVO> list = EasyExcel.read(inputStream).head(DemoDataVO.class).sheet().doReadSync();
        if (list == null || list.size() == 0) {
            throw new RuntimeException("导入数据不能为空");
        }
        log.info("导入数据:{}", list);
    }
导入数据:[DemoDataVO(name=张三, subject=语文, score=90), DemoDataVO(name=张三, subject=数学, score=80), DemoDataVO(name=王五, subject=英语, score=70), DemoDataVO(name=王五, subject=政治, score=85), DemoDataVO(name=李四, subject=历史, score=88), DemoDataVO(name=马六, subject=历史, score=77)]
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyExcel是一款基于注解的Excel读写库,可以方便地进行Excel导入导出操作。如果要对相同对象属性进行合并,可以使用EasyExcel的`@ExcelProperty`注解中的`index`属性来指定相同属性的号。 例如,有一个`User`类: ```java public class User { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄", index = 1) private Integer age; @ExcelProperty(value = "性别", index = 2) private String gender; @ExcelProperty(value = "地址", index = 3) private String address; // getters and setters } ``` 如果要对相同的`name`属性进行合并,可以将它们的`@ExcelProperty`注解中的`index`属性设置为相同的值,如下所示: ```java public class User { @ExcelProperty(value = "姓名", index = 0) private String name; @ExcelProperty(value = "年龄", index = 1) private Integer age; @ExcelProperty(value = "性别", index = 2) private String gender; @ExcelProperty(value = "地址", index = 3) private String address; @ExcelProperty(value = "备注", index = 4) private String comment; // getters and setters } ``` 在导出Excel时,EasyExcel会自动将相同号的属性值进行合并,生成如下的Excel表格: | 姓名 | 年龄 | 性别 | 地址 | 备注 | | ------ | ---- | ---- | ------------- | ------------------------------------- | | 张三 | 18 | 男 | 北京市朝阳区 | 第一行备注<br/>第二行备注<br/>第三行备注 | | 李四 | 20 | 女 | 上海市浦东新区 | 第一行备注 | | 王五 | 22 | 男 | 广州市天河区 | | | 赵六 | 24 | 女 | 深圳市福田区 | 第一行备注<br/>第二行备注 | 可以看到,相同姓名的三个用户的备注信息被合并到了同一中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值