apache-poijxls

JXLS auto fit row height according to the content


I'm using JXLS 2.3.0 with apache poi implementation.
And I use following code to create excel :

try{
   InputStream is = ObjectCollectionDemo.class.getResourceAsStream("/template.xls")
   OutputStream os = new FileOutputStream("target/output.xls")  
   Context context = new Context();
   context.putVar("employees", employees);
   JxlsHelper.getInstance().processTemplate(is, os, context);

   }

my generated excel file looks like next :

enter image description here

As above screenshot shows, the first 'Name' value only display partial.

But what I want is :

enter image description here

That is the content in excel cell can be wrapped and the row height can auto fit the cell content.

How can I do that? Thanks in advance.

-------------- Updated -----------------

the solution is:

  1. did as @Andy said
  2. format the corresponding cell as wrap text in your template file
  3. (optional) after step 1 and 2, the 99% info of cell content can be shown, but still miss some. Then I open the template file and found it looks like next:

enter image description here

we can found that the } of ${a.name} is on the new line, change it to:

enter image description here

that is make ${a.name} is on one line, then all content can be shown.


Solution

  • I know this post is quite old, but i stumbled upon it as one of the first Google hits, and want to share my solution.

    I implemented the auto-row-height feature for MS Excel 2010 in 3 steps.

    Create a Command:

    public class AutoRowHeightCommand extends AbstractCommand {
    
        // ... left out boilerplate
    
        @Override
        public Size applyAt(CellRef cellRef, Context context) {
            Size size = this.area.applyAt(cellRef, context);
    
            PoiTransformer transformer = (PoiTransformer) area.getTransformer();
            Row row = transformer.getWorkbook().getSheet(cellRef.getSheetName()).getRow(cellRef.getRow());
            row.setHeight((short) -1);
    
            return size;
        }
    }
    

    Configure the command to be used

    // static method call:
    XlsCommentAreaBuilder.addCommandMapping("autoRowHeight", AutoRowHeightCommand.class);
    
    JxlsHelper.getInstance().processTemplate(is, os, context);
    

    Make use of the command

    In the template.xlsx file edit the cell-comment that already contains the loop-command, and add the autoRowHeight command as a new line, e.g.:

    jx:each(items="myitems", var="i", lastCell="B4")
    jx:autoRowHeight(lastCell="B4")
    

    Thanks to Leonid Vysochyn and Franz Frühwirth, who lead me to this solution.