Merge and align center cell using apache poi

梦想与她 提交于 2019-12-04 23:49:10

My solution was to merge the cells by their positions, then created a cell (reference to the first block of the merged cells) to assign a value and then set the alignment throught the CellUtil

// Merges the cells
CellRangeAddress cellRangeAddress = new CellRangeAddress(start, start, j, j + 1);
sheet.addMergedRegion(cellRangeAddress);

// Creates the cell
Cell cell = CellUtil.createCell(row, j, entry.getKey());

// Sets the allignment to the created cell
CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);

Merge like:::

 Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

For aligning also check the below official link of Apache poi:::

http://poi.apache.org/spreadsheet/quick-guide.html#Alignment

shrey

After study I found that after merging 7 cells, merged cell id will be 0 so I applied following style to cell id 0 using following style.

headerStyle.setAlignment(headerStyle.ALIGN_CENTER);

As per my understanding, you have start and end cells for merging and you want to merge the cell ranges and align the cell content. If I am right, you can use the following method:

/**
 * @param startCell: first cell of merging area
 * @param endCell: last cell of merging area
 */

public static void mergeAndAlignCenter(HSSFCell startCell, HSSFCell endCell){
    //finding reference of start and end cell; will result like $A$1
    CellReference startCellRef= new CellReference(startCell.getRowIndex(),startCell.getColumnIndex());
    CellReference endCellRef = new CellReference(endCell.getRowIndex(),endCell.getColumnIndex());
    // forming string of references; will result like $A$1:$B$5 
    String cellRefernce = startCellRef.formatAsString()+":"+endCellRef.formatAsString();
    //removing $ to make cellRefernce like A1:B5
    cellRefernce = cellRefernce.replace("$","");
    //passing cellRefernce to make a region 
    CellRangeAddress region = CellRangeAddress.valueOf(cellRefernce);
    //use region to merge; though other method like sheet.addMergedRegion(new CellRangeAddress(1,1,4,1));
    // is also available, but facing some problem right now.
    startCell.getRow().getSheet().addMergedRegion( region );
    //setting alignment to center
    CellUtil.setAlignment(startCell, wb, CellStyle.ALIGN_CENTER);
}

Well what worked for me is to set all the merged cells' Cellstyle to CENTER ALIGN. Whether you put the XSSFSheet.addMergedRegion() method before or after setting the cellstyle values to center don't matter.

    private void insertXlsHeader(XSSFSheet sheet){
    ....
    //first cell for row1       
    cell = row1.createCell(colstart);
    cell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
    cell.setCellValue("COURSES");
    setHeaderCellStyle(sheet,cell);

    //first cell for row2
    cell = row2.createCell(colstart);
    setHeaderCellStyle(sheet,cell);

    //first cell for row3
    cell = row3.createCell(colstart);
    setHeaderCellStyle(sheet,cell);

    //merged the first cells of rows 1 to 3
    sheet.addMergedRegion(new CellRangeAddress(ROW1, ROW3, colstart, colstart));
    ...
    }

private void setHeaderCellStyle(XSSFSheet sheet,org.apache.poi.ss.usermodel.Cell cell) {
    CellStyle s = null;

        s = sheet.getWorkbook().createCellStyle();
        cell.setCellStyle(s);

    Font f = sheet.getWorkbook().createFont();

    f.setBoldweight(Font.BOLDWEIGHT_BOLD);


    s.setBorderBottom(CellStyle.BORDER_THIN);
    s.setBorderLeft(CellStyle.BORDER_THIN);
    s.setBorderRight(CellStyle.BORDER_THIN);
    s.setBorderTop(CellStyle.BORDER_THIN);
    s.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    s.setAlignment(CellStyle.ALIGN_CENTER);
    s.setFont(f);

}

This worked for me and I think it's cleaner:

/**
 * Merge and center the cells specified by range
 * @param startCell the first cell in the cells to be merged
 * @param range the range of the cells to be merged
 */
private static void mergeAndCenter(Cell startCell, CellRangeAddress range) {
    startCell.getSheet().addMergedRegion(range);
    CellStyle style = startCell.getSheet().getWorkbook().createCellStyle();
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    startCell.setCellStyle(style);
}

As answered above, merging cells can be achieved using

sheet.addMergedRegion(new CellRangeAddress(frstRow, lastRow, firstColumnIndex, lastColumnIndex));

But for aligning cells vertically,recently I faced similar issue and I tried above answer, but using

CellUtil.setAlignment(dataCell, workbook, CellStyle.VERTICAL_CENTER);

aligned Date formatted cells to Horizontal Left aligned. So I used following method to set only Vertical Alignment of Cell content.

CellUtil.setCellStyleProperty(dataCell, workbook,CellUtil.VERTICAL_ALIGNMENT,CellStyle.VERTICAL_CENTER);

I hope this helps!!

Happy Coding

Mahaveer Jangir

Use

style.setVerticalAlignment()

to set the vertical alignments instead of

style.setAlignment().                             
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!