简体   繁体   English

使用 Apache POI 合并 Excel 中的单元格

[英]Merging cells in Excel using Apache POI

Is there any other way to merge cells in Excel using Apache POI library?有没有其他方法可以使用 Apache POI 库合并 Excel 中的单元格?

I was trying using the following, but its not working我正在尝试使用以下内容,但它不起作用

// selecting the region in Worksheet for merging data
CellRangeAddress region = CellRangeAddress.valueOf("A" + rowNo + ":D"
            + rowNo);

// merging the region
sheet1.addMergedRegion(region);

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);您可以使用sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4));示例sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2.将从 B2 合并到 E2。 Remember it is zero based indexing (ex. POI version 3.12).请记住,它是基于零的索引(例如 POI 版本 3.12)。

for detail refer BusyDeveloper's Guide有关详细信息,请参阅BusyDeveloper's Guide

You can use :您可以使用 :

sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));

Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.确保 CellRangeAddress 与其他合并区域不重合,因为这会引发异常。

  • If you want to merge cells one above another, keep column indexes same如果您想将单元格上下合并,请保持列索引相同
  • If you want to merge cells which are in a single row, keep the row indexes same如果要合并单行中的单元格,请保持行索引相同
  • Indexes are zero based索引从零开始

For what you were trying to do this should work:对于您尝试执行的操作,应该可以:

sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));

最佳答案

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

I create a method that merge cells and put border if you want.如果需要,我创建了一种合并单元格并放置边框的方法。

protected void setMerge(Sheet sheet, int numRow, int untilRow, int numCol, int untilCol, boolean border) {
    CellRangeAddress cellMerge = new CellRangeAddress(numRow, untilRow, numCol, untilCol);
    sheet.addMergedRegion(cellMerge);
    if (border) {
        setBordersToMergedCells(sheet, cellMerge);
    }

}  

protected void setBordersToMergedCells(Sheet sheet, CellRangeAddress rangeAddress) {
    RegionUtil.setBorderTop(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderLeft(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderRight(BorderStyle.MEDIUM, rangeAddress, sheet);
    RegionUtil.setBorderBottom(BorderStyle.MEDIUM, rangeAddress, sheet);
}

syntax is:语法是:

sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));

Example:例子:

sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));

Here the cell 0 to cell 5 will be merged of the 4th row.这里单元格 0 到单元格 5 将合并到第 4 行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM