/** * Compute width of a column based on a subset of the rows and return the result * * @param sheet the sheet to calculate * @param column 0-based index of the column * @param useMergedCells whether to use merged cells * @param firstRow 0-based index of the first row to consider (inclusive) * @param lastRow 0-based index of the last row to consider (inclusive) * @return the width in pixels */ public static double getColumnWidth( Sheet sheet, int column, boolean useMergedCells, int firstRow, int lastRow) { AttributedString str; TextLayout layout; Workbook wb = sheet.getWorkbook(); DataFormatter formatter = new DataFormatter(); Font defaultFont = wb.getFontAt((short) 0); str = new AttributedString(String.valueOf(defaultChar)); copyAttributes(defaultFont, str, 0, 1); layout = new TextLayout(str.getIterator(), fontRenderContext); int defaultCharWidth = (int) layout.getAdvance(); double width = -1; for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) { Row row = sheet.getRow(rowIdx); if (row != null) { Cell cell = row.getCell(column); if (cell == null) { continue; } double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells); width = Math.max(width, cellWidth); } } return width; }