Wednesday, August 4, 2010

JBoss Seam Excel export as HttpServletResponse

JBoss Seam provides the ability to export to excel using the built-in libraries. Everything good until they want to do something custom. Then the trouble begins.


The solution is to use external library we know. One of the best is JExcelApi. We join in the usual way jxl.jar file to your project. Now we can start to write code for an Excel file generation. I will not describe the details of this lib. However I would like to show how the JBoss Seam display in the browser to download a file generated by the user.

Write a method which generates a file:
 
public void downloadXLSExport() {
   HttpServletResponse response = (HttpServletResponse) extCtx.getResponse();
   response.setContentType("application/vnd.ms-excel");
   response.addHeader("Content-disposition","attachment; filename=export.xls");
   OutputStream outputStream = null;
   try {
      outputStream = response.getOutputStream();
      WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
      WritableSheet sheet = workbook.createSheet("First Sheet", 0);
      sheet.addCell(new Label(i, 0, "Something"));
      workbook.write();
      workbook.close();
      outputStream.flush();
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      if (outputStream != null) {
         try {
            outputStream.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
         facesContext.responseComplete();
       }
   }
}

Now what left for us is calling from the xhtml file as shown below:


<h:form id="excelExport">
<h:commandLink value="Excel export"
action="#{exportModelStdHome.downloadXLSExport()}" />
</h:form>
 
Remember to place a call to form a <h:form>

No comments:

Post a Comment