Export to Excel from Java using POI
Here is some sample code to export data from Java to Excel. You can download the needed jar files from this website: http://poi.apache.org/. They currently are in work to support the new Office 2007 format. The POIFSFileSystem will have a path that points to the location of your excel file you will be populating with the data.
Code Struts Action example
public ActionForward exportXL(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try
{
OIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
System.getProperty("catalina.home")+"/webapps/Diamond/WEB-INF/classes/Template.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row=null;
HSSFCell cell = null;
row = sheet.createRow(1);
cell = getOrCreateCell(row, (short) 0);
cell.setCellValue( "Put Data Here") ;
cell = getOrCreateCell(row, (short) 1);
cell.setCellValue("Put Data Here");
cell = getOrCreateCell(row, (short) 2);
cell.setCellValue("Put Data Here");
response.setHeader(HEADER_CONTENT_DISPOSITION,"attachment; filename=View.xls");
response.setHeader(HEADER_CONTENT_TYPE, "application/vnd.ms-excel");
// Write the output to a file
ServletOutputStream fileOut = response.getOutputStream();
wb.write(fileOut);
fileOut.close();
}
catch(Exception e)
{
}
return null;
}

0 comments:
Post a Comment