导出到 Excel JSF 和 PrimeFaces
使用 JDK 1.6、JSF 2.1、PrimeFaces 2.2.1、POI 3.2 和 Apache Tomcat 7
我正在尝试设置一个servlet,以允许根据用户选择下载excel文件。Excel 文档是在运行时创建的。
没有错误,代码确实进入了servlet。
我点击按钮,没有任何反应。我没有使用PrimeFaces使用的数据表导出,因为我需要对Excel文档中的数据进行重新排序和自定义格式设置。
ExportExcelReports.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=\"my.xls\"");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(0.0);
FileOutputStream out = new FileOutputStream("my.xls");
workbook.write(out);
out.close();
}
ProjectReportBean.java
public void getReportData() {
try {
FacesContext ctx = FacesContext.getCurrentInstance();
ExternalContext ectx = ctx.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ectx.getRequest();
HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
RequestDispatcher dispatcher = request.getRequestDispatcher("/ExportExcelReports");
dispatcher.forward(request, response);
ctx.responseComplete();
} catch (Exception e) {}
}
索引.xhtml
<h:form id="reportsForm">
<h:outputLabel for="report" value="Reports" /><br />
<h:selectOneMenu id="report" value="#{projectReportBean.selectedReport}" required="true" requiredMessage="Select Report">
<f:selectItem itemLabel="---" noSelectionOption="true" />
<f:selectItems value="#{projectReportBean.reports}" />
</h:selectOneMenu>
<p:commandButton action="#{projectReportBean.getReportData}" value="Export" update="revgrid" />
</h:form>