EasyExcel 单元格合并

1. 继承AbstractMergeStrategy,重写merge方法

    参数介绍:

     countryCount 合并行数集合。 如下图 list则为6,5。同理productTypeCount

     EasyExcel 单元格合并_第1张图片

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
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;

public class MyMergeStrategy extends AbstractMergeStrategy {

    private Sheet sheet;
    private List countryCount;
    private List productTypeCount;
    public MyMergeStrategy(List countryCount,List productTypeCount) {
        this.countryCount = countryCount;
        this.productTypeCount = productTypeCount;
    }

    // 按照分组将各种类别分别合并成一个单元格
    private void mergeCountryColumn(Integer index) {
        Integer rowCnt = 1;
        for (Integer count : countryCount) {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCnt, rowCnt + count - 1, index, index);
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCnt += count;
        }
    }
    // 按照分组将各种类别分别合并成一个单元格
    private void mergeProductTypeColumn(Integer index) {
        Integer rowCnt = 1;
        for (Integer count : productTypeCount) {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCnt, rowCnt + count - 1, index, index);
            sheet.addMergedRegionUnsafe(cellRangeAddress);
            rowCnt += count;
        }
    }


    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        if (cell.getRowIndex() == 1) {
            switch (cell.getColumnIndex()) {
                case 0:
                    this.mergeCountryColumn(0);
                    break;
                case 1:
                    this.mergeProductTypeColumn(1);
                    break;
                default:
                    break;
            }
        }
    }
}

2. Excel导出

EasyExcel.write(response.getOutputStream(), clazz).registerWriteHandler(abstractMergeStrategy).excelType(ExcelTypeEnum.XLSX).sheet(sheetName);

你可能感兴趣的:(Excel,EasyExcel,Poi,java,蓝桥杯,开发语言)