在POI XSSF工作簿中添加边框的合并区域

人气:1,216 发布:2022-09-15 标签: java apache-poi xssf poi-hssf

问题描述

我使用的Apache POI 3.7和我需要把边框的单元格区域或合并区域。

I'm using apache poi 3.7 and I need to put border to a range of cells or merged region.

我怎么能申请边框合并区域时表和工作簿类型是XSSF。在HSSF型我用RegionUtil- / HSSFRegionutil,但如果使用XSSF的第一个对象(Regionutil)键入它不工作,并提出一个黑色的背景色的单元格范围。

how can I to apply border to a merged region when the sheet and workbook type is XSSF. In HSSF type I use RegionUtil-/HSSFRegionutil, but if use the first object (Regionutil) in XSSF type its doesn't works and puts a black background color to the range of cells.

Regionutil ussually适用于的CellRangeAddress,我不觉得这个故障信息。我不知道,如果CellRangeAddres导致此。

Regionutil ussually works with CellRangeAddress and i don't find information about this trouble. I don't know if the CellRangeAddres causes this.

推荐答案

在为了做到这一点,你必须空白单元格添加到每一个细胞在合并后的区域,再加入适当的边界每个单元格。例如,下面的code将在同一行中创建5个细胞的合并区域,与周围的整个合并的区域的边界,和在该区域的文本居中。

In order to do this, you have to add a blank cell to every cell in the merged region, then add the appropriate borders to each cell. For example, the following code will create a merged region of 5 cells in the same row, with a border around the whole merged region, and the text centred in the region.

XSSFWorkbook wb = new XSSFWorkbook();
CellStyle borderStyle = wb.createCellStyle();
borderStyle.setBorderBottom(CellStyle.BORDER_THIN);
borderStyle.setBorderLeft(CellStyle.BORDER_THIN);
borderStyle.setBorderRight(CellStyle.BORDER_THIN);
borderStyle.setBorderTop(CellStyle.BORDER_THIN);
borderStyle.setAlignment(CellStyle.ALIGN_CENTER);
Sheet sheet = wb.createSheet("Test Sheet");
Row row = sheet.createRow(1);
for (int i = 1; i <= 5; ++i) {
    Cell cell = row.createCell(i);
    cell.setCellStyle(borderStyle);
    if (i == 1) {
        cell.setCellValue("Centred Text");
    } 
}
sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 5));

214