[alibaba/easyexcel]复杂头写入,建议默认按主标题分组,不同主标题下的同名标题不要合并

2024-05-09 59 views
9

public class ComplexHeadData { @ExcelProperty({"主标题1", "字符串标题"}) private String string; @ExcelProperty({"主标题2", "字符串标题"}) private Date date; @ExcelProperty({"主标题2", "数字标题"}) private Double doubleData; }

这样导出的结果 image 建议默认按主标题分组,不同主标题下的同名标题不要合并

回答

5

设置 automaticMergeHead 不自动合并头

3

我目前就是设置这个,然后单独指定合并表头单元格的,我只是觉得你们自动合并逻辑是不是可以优化一下

5

`package com.hsit.nts.base.easyexcel.handler;

import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.write.handler.CellWriteHandler; import com.alibaba.excel.write.metadata.holder.WriteSheetHolder; import com.alibaba.excel.write.metadata.holder.WriteTableHolder; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

/**

  • 单元格合并处理
  • @author xxx
  • @date 2022/11/08 */ public class CellMergeStrategy implements CellWriteHandler {

    private final int columnIndex;

    public CellMergeStrategy(int columnIndex) { this.columnIndex = columnIndex; }

    @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) { int curRowIndex = cell.getRowIndex(); int curColIndex = cell.getColumnIndex(); //遍历数据行数据,并移除合并 if (curRowIndex >= columnIndex && curColIndex > 0) { removeChildTitleMerge(writeSheetHolder, curRowIndex, curColIndex); } }

    private void removeChildTitleMerge(WriteSheetHolder writeSheetHolder, int curRowIndex, int curColIndex) { Sheet sheet = writeSheetHolder.getSheet(); List mergeRegions = sheet.getMergedRegions(); //遍历合并单元格,并移除合并 for (int i = 0; i < mergeRegions.size(); i++) { CellRangeAddress cellRangeAddr = mergeRegions.get(i); //若单元格已经被合并,则移除合并的单元格 if (cellRangeAddr.isInRange(curRowIndex, curColIndex) && cellRangeAddr.isInRange(curRowIndex, curColIndex + 1)) { sheet.removeMergedRegion(i); break; } } }

}

`

EasyExcel.write(os).head(headList).registerWriteHandler(cellMergeStrategy).sheet(StringUtils.isEmpty(title) ? "sheet1" : title).doWrite(dataList);