Tuesday, July 16, 2013

Export to Excel in Java



Export to Excel is one of the common feature in a typical web based application. There are many approaches to accomplish it. The approach which I am proposing does not need any third party library to export to excel. It used XML based excel file. Means it would be a plain text (xml). No need for any office API or third party API.

 Create a JSP page(ExportToExcel.jsp) for exporting data to Excel.  Source page will direct to ExportToExcel.jsp page.

Set appropriate Content Type and Header in ExportToExcel.jsp file.
response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=ExcelFile.xml"); 
Output excel file would be ExcelFile.xml. You can change file name as per your need. However file extension should be "xml". Though it's extension is XML, window OS will treat it as Excel file based on the content of the file. We will see that below.
"attachment": this option will let user download excel file. If you choose to open excel file then change "attachment" to "inline".

Windows OS will treat xml file as excel based on  in XML content.
In the below example has 13 columns. All the rows are generated in for loop.