同一行中的多个单元格alignment(Apache POI)

我正在使用Apache POI 3.7,我试图创build一个单元格有左alignment和其他单元格中心alignment的行。

我试过了:

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

我也试过:

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

无论如何,当我生成Excel文档时,行中的所有单元格左alignment或居中alignment,但不混合。

我甚至不知道是否有可能做我想要的。

谢谢

所以它看起来像你有一个单元格样式,并不断改变它左和中心alignment。 单元格共享样式,所以如果您更改一个单元格的样式,它会更改样式已分配给的所有单元格。 要获得多个更改,您需要多个样式

 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(); 

另外还有一点需要注意的是,你可以使用的风格有限,所以如果你要创build一个大的表单,你必须共享它们。

根据Cell .setCellStyle(CellStyle样式)方法的javadoc,样式应该是通过调用Workbook上的createCellStyle()方法创build的CellStyle。 请尝试以下方法:

 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); } }