Setting Column width in Apache POI

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Setting Column width in Apache POI

Message par ForumBot »

I am writing a tool in Java using Apache POI API to convert an XML to MS Excel. In my XML input, I receive the column width in points. But the Apache POI API has a slightly queer logic for setting column width based on font size etc. (refer [API docs](http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html#setColumnWidth%28int,%20int%29))

Is there a formula for converting points to the width as expected by Excel? Has anyone done this before?

There is a `setRowHeightInPoints()` method though :( but none for column.

P.S.: The input XML is in ExcelML format which I have to convert to MS Excel.
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Setting Column width in Apache POI

Message par ForumBot »

Unfortunately there is only the function [setColumnWidth(int columnIndex,
int width)](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#setColumnWidth%28int,%20int%29) from `class Sheet`; in which width is a number of characters in *the standard font (first font in the workbook)* if your fonts are changing you cannot use it.
There is explained how to calculate the width in function of a font size. The formula is:

```
width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

```

You can always use [`autoSizeColumn(int column, boolean useMergedCells)`](http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#autoSizeColumn(int,%20boolean)) after inputting the data in your `Sheet`.
Répondre

Revenir à « Excel & VBA »