Friday, September 19, 2008

Export Excel file under JSF

I think maybe it is a good idea to write down how to export Excel file under JSF. I'm using Myfaces 1.2 and Apache POI 3.1

The basic code should look like:
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse)context.getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename=job.xls");
response.setHeader("Pragma", "no-cache");
try{
OutputStream os = response.getOutputStream();

int rowIndex = 0;

// Create Excel Object
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet 1");

// Print out configuration, optional
HSSFPrintSetup ps = sheet.getPrintSetup();
ps.setFitWidth((short)1);

// Define cell style, optional
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setWrapText(true);

// Create a row
HSSFRow row = sheet.createRow(rowIndex++);
// Create cells
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(new HSSFRichTextString("Id") );
cell.setCellStyle(cellStyle);
cell = row.createCell((short)1);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString("Name") );
cell = row.createCell((short)2);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString("Email") );
cell.setCellStyle(cellStyle);
cell = row.createCell((short)3);
cell.setCellValue(new HSSFRichTextString("Phone Number") );
cell.setCellStyle(cellStyle);
// Your own code ...

wb.write(ops);
os.flush();
os.close();
}
catch(IOException ioe) {
// Handle exception ...
}

FacesContext.getCurrentInstance().responseComplete();

Tell the truth, the default setting of POI is not very smart. In real project you may need add some extra code to beautify your excel. I list some useful settings here.

Print Configuration
Fit your Excel the width of one page
HSSFPrintSetup ps = sheet.getPrintSetup();
ps.setFitWidth((short)1);
Set default orientation to landscape
HSSFPrintSetup ps = sheet.getPrintSetup();
ps.setLandscape(true);
Auto break
sheet.setAutobreaks(true);

Cell Configuration
Auto wrap text
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setWrapText(true);
Alignment
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
Vertical Alignment
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
You can get more detail information of POI by checking out the following link:
http://poi.apache.org/hssf/quick-guide.html

No comments: