简体   繁体   English

多个单元格在同一行中对齐(Apache POI)

[英]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. 我正在使用Apache POI 3.7,并试图创建一行,其中某些单元格左对齐,而其他单元格居中对齐。

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. 无论如何,当我生成Excel文档时,该行中的所有单元格都左对齐或居中对齐,但没有混合。

I don't even know if it's possible to do what I'm trying. 我什至不知道是否有可能做我正在尝试的事情。

Thank you 谢谢

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. 在此需要额外说明的一点是,您只能使用几种样式,因此,如果要创建较大的图纸,则必须共享它们。

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. 根据Cell .setCellStyle(CellStyle style)方法的javadoc,样式应为通过调用工作簿上的createCellStyle()方法创建的CellStyle。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM