How to write a jXLS template and where to write it

Raaz picture Raaz · Jun 5, 2012 · Viewed 14.2k times · Source

I'm trying to use jXLS to export data from a list to an Excel sheet. I need to create an Excel template using jXLS and print out a list of data using that template. I have a Bean class called Department and I need to use a forEach statement to loop through the list and write data to the Excel sheet.

Can someone please tell me how and where I can write my Excel template? I know my code inside should look something like this -

            <jx:forEach items="${departments}" var="department">
                ${department.name} | ${department.chief}
            </jx:forEach>

Answer

Sanjay Bharwani picture Sanjay Bharwani · Jul 5, 2012

You need to create an Excel Template file where in you define your basic structure which you need to repeat for number of objects in the collection.

The code

<jx:forEach items="${departments}" var="department">
                ${department.name} | ${department.chief}
            </jx:forEach>

will go in that template excel.

Then you need to use JXLS API in java code to generated the excel from this template.

Map contextBeans = new HashMap();
contextBeans.put("departments", departmentList);
xlsTransformer.transformXLS(xlsTemplateFileURL.getPath(), contextBeans, reportFileURL.getPath());

This code will create the excel file out of the template file populated with the collection loaded in contextBeans Map.