Auto size height for rows in Apache POI
Asked Answered
F

11

46

I am inputting values into a spreadsheet using Apache POI. These values have newlines, and I was able to use this code successfully:

CellStyle style = cell.getCellStyle()
style.setWrapText(true)
cell.setCellStyle(style)

Unfortunately, while the text is wrapping correctly, the rows are not always growing in height enough to show the content. How do I ensure that my rows are always the correct height?

Florafloral answered 2/10, 2013 at 19:51 Comment(0)
S
32
currentRow.setHeight((short)-1)

Works for XSSFCell and Excel 2013

Steadman answered 18/3, 2015 at 19:41 Comment(3)
Shockingly, this also worked in NPOI (the .NET implementation) and opens correctly in Excel 2013. Syntax is slightly different: row.Height = -1;Teakettle
This solution does not work for Ubuntu's LibreOffice version 5.1.6.2 and POI 3.17, but it does work if document is opened with MSExcelSaimon
Exactly the good answer!Ancell
K
22
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet =  workbook.createSheet("FirstSheet");  
HSSFRow rowhead=   sheet.createRow((short)0);
HSSFCellStyle style = workbook.createCellStyle();
style.setWrapText(true);
row.setRowStyle(style);
row.getCell(0).setCellStyle(style);

The above code will generate dynamic height of rows.

Kauai answered 9/2, 2015 at 10:37 Comment(7)
Eee...no this does not work. At least not on Ubuntu Linux with Libre OfficeNarrows
@ed22, doesn't work for me as well. Same environment.Violaviolable
This is a Libre Office related issue. Spreadsheet opens correctly in MS ExcelNarrows
I also have to use Libre Office and this doesn't solve the row height problem. Is there any way to make Libre Office display better row heights? I have a cell with a slightly bigger font in it. Libre Office doesn't increase the row height automatically, whereas MS Office and Open Office increase the height in a nice way.Dodecasyllable
style.setWrapText(true) was enough in my case! There are merged cells present.Damascus
doesn't work with MS Office 365Laundromat
Hi wraps the text for cells do not have new line as well. How to wrap the text only for cell contain new line?Gibrian
B
5

The only way I got this to work was write my own implementation to calculate the row height. The code is now released as the Taro project, so you could use that. It has numerous convenience methods to let you write an Excel file in far fewer lines of code.

If you prefer to put the implementation in your own code, you can find it in the SpreadsheetTab class. There is an autoSizeRow(int rowIndex) method half way down. It basically iterates down the row and for each cell finds the number of lines of text, then uses the font size to calculate the optimal cell height. It then sets the row height to the height of the tallest cell.

Bonanza answered 3/10, 2013 at 17:8 Comment(1)
Note: This only works with cells that have \n on their values. You have to determine where to place the \n on your own. If there is none, the row will have one line heightBiblicist
S
4

See all this link, which provides some code to manually calculate the correct height for a row, based on the column width and cell content. I've not personally tested it. Also pasted below for convenience:

// Create Font object with Font attribute (e.g. Font family, Font size, etc) for calculation
java.awt.Font currFont = new java.awt.Font(fontName, 0, fontSize);
AttributedString attrStr = new AttributedString(cellValue);
attrStr.addAttribute(TextAttribute.FONT, currFont);

// Use LineBreakMeasurer to count number of lines needed for the text
FontRenderContext frc = new FontRenderContext(null, true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);
int nextPos = 0;
int lineCnt = 0;
while (measurer.getPosition() < cellValue.length())
{
    nextPos = measurer.nextOffset(mergedCellWidth); // mergedCellWidth is the max width of each line
    lineCnt++;
    measurer.setPosition(nextPos);
}

Row currRow = currSht.getRow(rowNum);
currRow.setHeight((short)(currRow.getHeight() * lineCnt));

// The above solution doesn't handle the newline character, i.e. "\n", and only
// tested under horizontal merged cells.
Siouan answered 20/1, 2014 at 18:3 Comment(1)
The last line must use either: row.getHeightInPoints() or currSht.getDefaultRowHeightInPoints() instead of "getHeight()"Narrows
R
3

In my case a robust solution was to calculate the number of lines and set the row height to a multiple of the default row height:

int numberOfLines = cell.getStringCellValue().split("\n").length;
row.setHeightInPoints(numberOfLines*sheet.getDefaultRowHeightInPoints());
Revue answered 30/6, 2021 at 10:55 Comment(1)
pointless since you get this even without new linesWoolson
P
2
cell.getRow().setHeight((short) -1);

Worked for HSSFCell in apache poi 3.9 or above

Primm answered 4/3, 2016 at 7:1 Comment(0)
S
1

It works in Excel 2010. I set the limit of cell length of 50 characters

    Row row = sheet.createRow(0);
    CellStyle style = workbook.createCellStyle();
    style.setWrapText(true);
    if (data.length() > 50) {
        for (int i = 1; i <= Math.abs(data.length() / 50); i++) {
            data = data.substring(0, i * 50) + "\n" + data.substring(i * 50);
        }
        Cell cell = row.createCell(0);
        row.setRowStyle(style);
        cell.setCellStyle(style);
        cell.setCellValue(data);
        sheet.autoSizeColumn(0);
    }
Sesquicentennial answered 21/4, 2019 at 9:5 Comment(1)
sooo no auto heightHobbs
H
0

You can't adjust cell height directly. But you can change the row's height

final HSSFSheet fs = wb.createSheet("sheet1");
final HSSFRow row0 = fs.createRow(0);
final HSSFCell cellA1 = row0.createCell(0);
row0.setHeight((short)700);
Huihuie answered 13/12, 2013 at 10:50 Comment(1)
This is not automatic sizing (auto-size), it is manual sizing.Lookthrough
O
-1

Row aitosize work for me:

cell.getRow().setHeight((short)0);

Here 0 for calculate autoheight.

Ochs answered 13/12, 2013 at 10:55 Comment(4)
This doesn't appear to work. When I open in Excel (2010), the row is simply zero height.Siouan
@GreenGiant, I don't use Windows and Excel. This solution work for OpenOffice. Also it problem to set automatically row height for merged cells in Excel (need macro for fix it).Ochs
Sadly, this will set to zero heigh a.k.a invisibleLaundromat
value -1 actually worked for meLaundrywoman
H
-1

Workaround for “LibreOffice Calc“ and “WPS Spreadsheet” with auto height for merged sells.

I add a column out to the right of a main document (In my case it was 32 column) Set width as all merged cells with same text. Set style WrapText to true Set style to Align Top Copy content which will be displayed in the merged cells Set that column to be hidden Set a row height = -1

A sample of code:

   private void applyRowHightWorkaroundForMergedCells(HSSFCell cell0) {
       HSSFSheet sheet = cell0.getSheet();
       HSSFRow row = cell0.getRow();
    
       String value = cell0.getStringCellValue();
       HSSFCell cell = row.createCell(32);
       sheet.setColumnWidth(32, 32000);
       cell.getCellStyle().setWrapText(true);
       cell.getCellStyle().setVerticalAlignment(VerticalAlignment.TOP);
       cell.setCellValue(value);
       sheet.setColumnHidden(32, true);
       row.setHeight((short) -1);
   }
Hedi answered 19/10, 2020 at 13:22 Comment(0)
C
-11

//we can use column width for sheet

Ex: sheet.setColumnWidth(0, 2000);
Carmancarmarthen answered 3/10, 2013 at 5:53 Comment(1)
The OP is asking about adjusting row height not column width.Siouan

© 2022 - 2024 — McMap. All rights reserved.