2015年11月26日 | Leave a comment 问题: 在JSF 列表页面有个按钮导出,点后下载excel 数据文件 解决: 使用apache POI 构建excel 文件使用 primeFace fileDownload 下载 xhtml: <h:commandButton value="导出用户22"> <p:fileDownload value="#{bean1.downloadFile()}"></p:fileDownload> </h:commandButton><br /> 123 <h:commandButton value="导出用户22"> <p:fileDownload value="#{bean1.downloadFile()}"></p:fileDownload></h:commandButton><br /> javabean: @Named(name="bean1") @RequestScoped pubilc class Bean1{ public StreamedContent downloadFile() throws IOException{ HSSFWorkbook b=new HSSFWorkbook(); HSSFSheet sheet= b.createSheet(); for(int i=0;i<100;++i){ HSSFRow row=sheet.createRow(i); HSSFCell cell=row.createCell(0); cell.setCellValue(i); } ByteArrayOutputStream os=new ByteArrayOutputStream(); b.write(os); ByteArrayInputStream is=new ByteArrayInputStream(os.toByteArray());//不能直接使用 b.getBytes(); DefaultStreamedContent ret= new DefaultStreamedContent( is ); ret.setName("userlist.xls"); ret.setContentType("application/vnd.ms-excel"); return ret; } } 123456789101112131415161718192021 @Named(name="bean1")@RequestScopedpubilc class Bean1{ public StreamedContent downloadFile() throws IOException{ HSSFWorkbook b=new HSSFWorkbook(); HSSFSheet sheet= b.createSheet(); for(int i=0;i<100;++i){ HSSFRow row=sheet.createRow(i); HSSFCell cell=row.createCell(0); cell.setCellValue(i); } ByteArrayOutputStream os=new ByteArrayOutputStream(); b.write(os); ByteArrayInputStream is=new ByteArrayInputStream(os.toByteArray());//不能直接使用 b.getBytes(); DefaultStreamedContent ret= new DefaultStreamedContent( is ); ret.setName("userlist.xls"); ret.setContentType("application/vnd.ms-excel"); return ret; }}