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