Charles Charles - 3 months ago 13
Java Question

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

Answer

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.