LoopMergeStrategy.java 2.0 KB
Newer Older
Z
zhuangjiaju 已提交
1 2 3 4 5 6 7 8 9 10
package com.alibaba.excel.write.merge;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import com.alibaba.excel.metadata.Head;

/**
 * The regions of the loop merge
Z
zhuangjiaju 已提交
11
 *
Z
zhuangjiaju 已提交
12
 * @author Jiaju Zhuang
Z
zhuangjiaju 已提交
13 14 15
 */
public class LoopMergeStrategy extends AbstractMergeStrategy {
    private int eachRow;
Z
zl 已提交
16
    private int columnCount;
Z
zhuangjiaju 已提交
17
    private int columnIndex;
Z
zhuangjiaju 已提交
18

Z
zhuangjiaju 已提交
19
    public LoopMergeStrategy(int eachRow, int columnIndex) {
Z
zl 已提交
20 21 22 23
        this(eachRow, 1, columnIndex);
    }

    public LoopMergeStrategy(int eachRow, int columnCount, int columnIndex) {
Z
zhuangjiaju 已提交
24 25 26
        if (eachRow < 1) {
            throw new IllegalArgumentException("EachRows must be greater than 1");
        }
Z
zl 已提交
27 28 29 30 31 32
        if (columnCount < 1) {
            throw new IllegalArgumentException("ColumnCount must be greater than 1");
        }
        if (columnCount == 1 && eachRow == 1) {
            throw new IllegalArgumentException("ColumnCount or eachRows must be greater than 1");
        }
Z
zhuangjiaju 已提交
33 34
        if (columnIndex < 0) {
            throw new IllegalArgumentException("ColumnIndex must be greater than 0");
Z
zhuangjiaju 已提交
35 36
        }
        this.eachRow = eachRow;
Z
zl 已提交
37
        this.columnCount = columnCount;
Z
zhuangjiaju 已提交
38
        this.columnIndex = columnIndex;
Z
zhuangjiaju 已提交
39 40 41
    }

    @Override
庄家钜's avatar
庄家钜 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (relativeRowIndex == null) {
            return;
        }
        Integer currentColumnIndex;
        if (head != null) {
            currentColumnIndex = head.getColumnIndex();
        } else {
            currentColumnIndex = cell.getColumnIndex();
        }
        if (currentColumnIndex == columnIndex && relativeRowIndex % eachRow == 0) {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(cell.getRowIndex(),
                cell.getRowIndex() + eachRow - 1, cell.getColumnIndex(), cell.getColumnIndex() + columnCount - 1);
            sheet.addMergedRegionUnsafe(cellRangeAddress);
Z
zhuangjiaju 已提交
56 57 58
        }
    }
}