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();Set default orientation to landscape
ps.setFitWidth((short)1);
HSSFPrintSetup ps = sheet.getPrintSetup();Auto break
ps.setLandscape(true);
sheet.setAutobreaks(true);
Cell Configuration
Auto wrap text
HSSFCellStyle cellStyle = wb.createCellStyle();Alignment
cellStyle.setWrapText(true);
HSSFCellStyle cellStyle = wb.createCellStyle();Vertical Alignment
cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
HSSFCellStyle cellStyle = wb.createCellStyle();You can get more detail information of POI by checking out the following link:
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
http://poi.apache.org/hssf/quick-guide.html
No comments:
Post a Comment