Charles
Charles

Reputation: 282

Multiple cell align in same row (Apache POI)

I'm using Apache POI 3.7 and I'm trying to create a row in which some cells have left align and other cells have center align.

I've tried:

if(isNumeric()){ cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); }else{ cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT); }

I also tried:

cellStyle.setAlignment((short)0) , cellStyle.setAlignment((short)1) ...

Anyhow, when I generate Excel document, all cells in the row are Left aligned or center aligned, but not mixed.

I don't even know if it's possible to do what I'm trying.

Thank you

Upvotes: 0

Views: 2740

Answers (2)

jmarkmurphy
jmarkmurphy

Reputation: 11473

So it looks like you have a single cell style and keep changing it between left and center aligned. Cells share styles, so if you change the style for one cell, it changes for all cells that the style has been assigned to. To get multiple allignments, you need multiple styles

Workbook wb = new XSSFWorkbook();
Sheet sh = wb.createSheet("Sheet1");
CellStyle left = wb.createCellStyle();
left.setAlignment(CellStyle.ALIGN_LEFT);
CellStyle center = wb.createCellStyle();
center.setAlignment(CellStyle.ALIGN_CENTER);

Row r1 = sh.createRow(1);
Cell c1 = r1.createCell(1);
c1.setCellStyle(left);
c1.setCellValue("Left justified text");
Cell c2 = r1.createCell(2);
c2.setCellStyle(center);
c2.setCellValue(1234);
Cell c3 = r1.createCell(3);
c3.setCellStyle(left);
c3.setCellValue("More Left Justified Text");

FileOutputStream fileOut = new FileOutputStream("CellAlignTest.xlsx");
wb.write(fileOut);
wb.close();
fileOut.close();

One additional note here, you have a limited number of styles to work with, so you have to share them if you are creating a large sheet.

Upvotes: 3

Palamino
Palamino

Reputation: 791

According to the javadoc for the Cell .setCellStyle(CellStyle style) method, the style should be a CellStyle created by calling the createCellStyle() method on the Workbook. Give the following a try:

CellStyle centeredStyle = workbook.createCellStyle();
centeredStyle.setAlignment(CellStyle.ALIGN_CENTER);

CellStyle leftStyle = workbook.createCellStyle();
leftStyle.setAlignment(CellStyle.ALIGN_LEFT);

Sheet sheet = workbook.getSheetAt(0);
for(Row row : sheet.rowIterator()) {
    for(Cell cell : row.cellIterator()) {
        CellStyle cellStyle = (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) ? centeredStyle : leftStyle;
        cell.setCellStyle(cellStyle);
    }
}

Upvotes: 1

Related Questions