Auto size height for rows in Apache POI

后端 未结 10 983
闹比i
闹比i 2020-12-08 18:47

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.g         


        
10条回答
  •  粉色の甜心
    2020-12-08 19:48

    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.
    

提交回复
热议问题