I experienced the exact issue you described and was able to find some success by explicitly setting the font via the Cell
style as suggested in some of the comments above (also here).
However, one thing I noticed is that autoSizeColumn
was still not taking into consideration the width of all cells. Particularly, I have a row of cells that are basically the column headers describing each column's data. These cells had the custom Font
applied successfully, but were still not being considered with respect to the column's width when autoSizeColumn
ran. There are differences, but I would have assumed they were irrelevant. For example, the headers had a different cell type from the rest of the data in the column... and the cell headers have different colors applied to make them stand out.
Having said that, try creating a sheet with just a very basic set of cell styles applied, and then try tweaking from there:
// Let's test with Arial, 10pt
Font testFont = workbook.createFont();
testFont.setFontName("Arial");
testFont.setFontHeightInPoints((short)10);
// We'll apply a very bare-bones style to our cells that just applies the Font
CellStyle testCellStyle = workbook.createCellStyle();
testCellStyle.setFont(testFont);
// Your real data cell creation would go here instead of my dummy code:
CreationHelper creationHelper = workbook.getCreationHelper();
Row testRow = thisSheet.createRow(0);
int currentColumn = 0;
Cell testCell = testRow.createCell(currentColumn++);
testCell.setCellStyle(testCellStyle);
testCell.setCellType(Cell.CELL_TYPE_STRING);
testCell.setCellValue(creationHelper.createRichTextString("Cell Data Goes Here");
testCell = testRow.createCell(currentColumn++);
testCell.setCellStyle(testCellStyle);
testCell.setCellType(Cell.CELL_TYPE_STRING);
testCell.setCellValue(creationHelper.createRichTextString("Your Real Code Won't Be This Redundant :)");
One final thought, if autoSizeColumn
is still doing unfortunate or inconsistent things to column widths, you could add a safety net to ensure that columns don't get smaller than the default:
int origColWidth = thisSheet.getColumnWidth(currentColumn);
thisSheet.autoSizeColumn(currentColumn);
// Reset to original width if resized width is smaller than default/original
if (origColWidth > thisSheet.getColumnWidth(currentColumn))
thisSheet.setColumnWidth(currentColumn, origColWidth);