JXL Cell Formatting

Viewed 54619

How to autofit content in cell using jxl api?

8 Answers

I know this is an old question at this point, but I was looking for the solution to this and thought I would post it in case someone else needs it.

CellView Auto-Size

I'm not sure why the FAQ doesn't mention this, because it very clearly exists in the docs.

My code looked like the following:

for(int x=0;x<c;x++)
{
    cell=sheet.getColumnView(x);
    cell.setAutosize(true);
    sheet.setColumnView(x, cell);
}

c stores the number of columns created
cell is just a temporary place holder for the returned CellView object
sheet is my WriteableSheet object

The Api warns that this is a processor intensive function, so it's probably not ideal for large files. But for a small file like mine (<100 rows) it took no noticeable time.

Hope this helps someone.

Kotlin's implementation

private fun sheetAutoFitColumns(sheet: WritableSheet, columnsIndexesForFit: Array<Int>? = null, startFromRowWithIndex: Int = 0, excludeLastRows : Int = 0) {
    for (columnIndex in columnsIndexesForFit?.iterator() ?: IntProgression.fromClosedRange(0, sheet.columns, 1).iterator()) {
        val cells = sheet.getColumn(columnIndex)
        var longestStrLen = -1
        if (cells.isEmpty()) continue
        for (j in startFromRowWithIndex until cells.size - excludeLastRows) {
            if (cells[j].contents.length > longestStrLen) {
                val str = cells[j].contents
                if (str == null || str.isEmpty()) continue
                longestStrLen = str.trim().length
            }
        }
        if (longestStrLen == -1) continue
        val newWidth = if (longestStrLen > 255) 255 else longestStrLen
        sheet.setColumnView(columnIndex, newWidth)
    }
}

example for use

sheetAutoFitColumns(sheet) // fit all columns by all rows
sheetAutoFitColumns(sheet, arrayOf(0, 3))// fit A and D columns by all rows 
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5)// fit A and D columns by rows after 5 
sheetAutoFitColumns(sheet, arrayOf(0, 3), 5, 2)// fit A and D columns by rows after 5 and ignore two last rows
Related