tags:

views:

1390

answers:

2

How to autofit content in cell using jxl api? Please help with example.

A: 

From the JExcelApi FAQ

How do I do the equivilent of Excel's "Format/Column/Auto Fit Selection"?

There is no API function to do this for you. You'll need to write code that scans the cells in each column, calculates the maximum length, and then calls setColumnView() accordingly. This will get you close to what Excel does but not exactly. Since most fonts have variable width characters, to get the exact same value, you would need to use FontMetrics to calculate the maximum width of each string in the column. No one has posted code on how to do this yet. Feel free to post code to the Yahoo! group or send it directly to the FAQ author's listed at the bottom of this page.

FontMetrics presumably refers to java.awt.FontMetrics. You should be able to work something out with the getLineMetrics(String, Graphics) method I would have though.

Cosmic Flame
+1  A: 

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.

clang1234