我正在使用 Apache POI 3.7,并且尝试创建一行,其中某些单元格左对齐,其他单元格居中对齐。
我已经尝试过:
if(isNumeric()){
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
}别的{
cellStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT);
}
我也尝试过:
cellStyle.setAlignment((短)0) , cellStyle.setAlignment((短)1) ...
无论如何,当我生成Excel文档时,该行中的所有单元格都是左对齐或居中对齐,但不是混合的。
我什至不知道是否可以做我正在尝试的事情。
谢谢
最佳答案
所以看起来你有一个单一的单元格样式,并不断在左对齐和居中对齐之间更改它。单元格共享样式,因此如果您更改一个单元格的样式,则该样式已分配到的所有单元格的样式都会更改。要获得多种对齐方式,您需要多种样式
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();
这里还有一点需要注意,您可以使用的样式数量有限,因此如果您要创建大型工作表,则必须共享它们。
关于java - 多个单元格在同一行中对齐(Apache POI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39018514/