Pregunta

When I set the alignment on a cell that's a number it aligns, when the cell is text it won't.

Workbook workbook = new XSSFWorkbook();
CreationHelper creationHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);

// doesn't
Cell richTextCell = row.createCell(0);
RichTextString richTextString = creationHelper.createRichTextString("So rich!");
richTextCell.setCellValue(richTextString);
CellStyle richTextCellStyle = richTextCell.getCellStyle();
richTextCellStyle.setAlignment(CellStyle.ALIGN_RIGHT);

// works
Cell numberCell = row.createCell(1);
numberCell.setCellValue(12.34);
CellStyle numberCellStyle = numberCell.getCellStyle();
numberCellStyle.setAlignment(CellStyle.ALIGN_RIGHT);


FileOutputStream fileOutputStream = new FileOutputStream("workbook.xlsx");
try {
    workbook.write(fileOutputStream);
} finally {
    fileOutputStream.close();
}
¿Fue útil?

Solución

I duplicated this behavior when creating an .xlsx workbook with an XSSFWorkbook. Interestingly, when I changed to an HSSFWorkbook, the behavior changed and both cells were aligned right.

I took a closer look at the .xlsx when I opened it in Excel. The Excel toolbar button that indicates "aligned right" was not highlighted for either cell, even though the number looked like it was aligned to the right. For reference, the toolbar button is in "Home", "Alignment" section, and looks like this (big closeup):

________
  ______
________
  ______
________
  ______

However, by default, all numbers in Excel are already right-aligned. It looks like for .xlsx workbooks, you can't just get the current cell style if it's the default cell style and modify it. You must create a new CellStyle, set its properties, and set the new cell style for the cell.

The following code works in .xls and .xlsx workbooks. Additionally, it also creates only one CellStyle object, to be used on all applicable cells, demonstrating the appropriate reuse of CellStyle objects.

CellStyle rightAligned = workbook.createCellStyle();
rightAligned.setAlignment(CellStyle.ALIGN_RIGHT);

Cell richTextCell = row.createCell(0);
RichTextString richTextString = creationHelper.createRichTextString("So rich!");
richTextCell.setCellValue(richTextString);
richTextCell.setCellStyle(rightAligned);

Cell numberCell = row.createCell(1);
numberCell.setCellValue(12.34);
numberCell.setCellStyle(rightAligned);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top