Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating the border for the merged cells in POI

Could anyone explain me how to create the borders for the merged cells using Apache POI?
The Code I'm using is only affecting one cell.

sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
Cell monthCell = subheaderRow.createCell(2);
monthCell.setCellValue(2);
monthCell.setCellStyle(styles.get("month"));



style = wb.createCellStyle();

style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
// style.setFillPattern(CellStyle.SOLID_FOREGROUND);
// style.setFont(monthFont);
styles.put("month", style);
like image 485
user3511026 Avatar asked May 08 '14 05:05

user3511026


People also ask

How do you add a border to a merged cell?

You need to assign same style (in your case style that includes the border) to each cell you are merging. My suggestion create a function that checks and corrects, sets style to all cells in the merging region. Here is example of my own: private static final XSSFColor COLOR_ORANGE = new XSSFColor(new java.

Does filter work on merged cells?

In some situation you can't work with workbook that consists of merged cells. To use Filter, Sort or other functions, you need to unmerge cells and put to all of them the data from merged cells.


1 Answers

This can be done as below:

public void doMerge(int rowIndex, int columnIndex, int rowSpan, int columnSpan) {
    Cell cell = sheet.getRow(rowIndex).getCell(columnIndex);
    CellRangeAddress range = new CellRangeAddress(rowIndex, rowIndex + rowSpan - 1, columnIndex, columnIndex
            + columnSpan - 1);

    sheet.addMergedRegion(range);

    RegionUtil.setBorderBottom(cell.getCellStyle().getBorderBottom(), range, sheet, sheet.getWorkbook());
    RegionUtil.setBorderTop(cell.getCellStyle().getBorderTop(), range, sheet, sheet.getWorkbook());
    RegionUtil.setBorderLeft(cell.getCellStyle().getBorderLeft(), range, sheet, sheet.getWorkbook());
    RegionUtil.setBorderRight(cell.getCellStyle().getBorderRight(), range, sheet, sheet.getWorkbook());

    RegionUtil.setBottomBorderColor(cell.getCellStyle().getBottomBorderColor(), range, sheet, sheet.getWorkbook());
    RegionUtil.setTopBorderColor(cell.getCellStyle().getTopBorderColor(), range, sheet, sheet.getWorkbook());
    RegionUtil.setLeftBorderColor(cell.getCellStyle().getLeftBorderColor(), range, sheet, sheet.getWorkbook());
    RegionUtil.setRightBorderColor(cell.getCellStyle().getRightBorderColor(), range, sheet, sheet.getWorkbook());
}
like image 184
Alan Hay Avatar answered Sep 24 '22 14:09

Alan Hay