2016-08-18 47 views
0

我使用的是Apache POI 3.7,我试图创建一行,其中一些单元格具有左对齐并且其他单元格具有中心对齐。多个单元格在同一行中对齐(Apache POI)

我已经试过:

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

我也试过:

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

总之,当我生成Excel文件,该行中的所有单元左对齐或中心对齐,但没有混合。

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

谢谢

回答

3

所以看起来你有一个单一的单元格样式,并保持左边和中间对齐之间改变它。单元格共享样式,所以如果您更改一个单元格的样式,它将更改为已分配样式的所有单元格。为了让多个allignments,需要多种样式

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

,还应注意,你有数量有限的风格一起工作,所以你必须,如果你正在创建一个大表分享。

+0

不知道单元格共享样式,你的代码就像我期待的那样工作!我还参考了最后一个注释,并且工作簿的样式限制是4.000。谢谢 – Charles

1

根据的Javadoc的细胞.setCellStyle(CellStyle风格)方法,风格应该是通过调用工作簿createCellStyle()方法创建一个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); 
    } 
}