Esporta in Excel JSF e Prime Faces
-
27-10-2019 - |
Domanda
Utilizzando JDK 1.6, JSF 2.1, Primefaces 2.2.1, POI 3.2 e Apache Tomcat 7
Sto cercando di impostare un servlet per consentire un download di un file Excel in base alla selezione dell'utente. Il documento Excel viene creato in fase di esecuzione.
Nessun errore e il codice entra nel servlet.
Faccio clic sul pulsante e non succede nulla. Non sto utilizzando l'esportazione dati di dati utilizzata da PrimeFaces perché devo eseguire il riordino e la formattazione personalizzata sui dati nel documento 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) {}
}
index.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>
Soluzione
Ci sono due problemi.
Il primo problema è che il <p:commandButton>
Invia per impostazione predefinita una richiesta AJAX. Questa richiesta è licenziata dal codice JavaScript. Tuttavia, JavaScript non può fare nulla con una risposta che contiene un download di file. A causa delle restrizioni di sicurezza JavaScript non può generare a Salva come dialogo o qualcosa del genere. La risposta è sostanzialmente totalmente ignorata.
Devi aggiungere ajax="false"
a <p:commandButton>
Per spegnere l'Ajax in modo che il pulsante scada una normale richiesta HTTP sincrona, oppure è necessario sostituirlo in base allo standard <h:commandButton>
.
<p:commandButton ajax="false" ... />
o
<h:commandButton ... />
Il secondo problema è che il tuo servlet non scrive affatto il file Excel alla risposta, ma invece a un file locale che viene archiviato nella directory di lavoro del server. Fondamentalmente, la risposta HTTP contiene niente. Devi passare HttpServletResponse#getOutputStream()
al WorkBook#write()
metodo.
workbook.write(response.getOutputStream());
Su una nota non correlata, mi chiedo come il servlet sia utile qui. Vuoi riutilizzarlo fuori da JSF? In caso contrario, non è necessariamente bisogno di inviare nel servlet, ma basta eseguire lo stesso codice nel metodo di azione di Bean. Quel vuoto catch
Anche il blocco non è bello. Lo dichiarerei solo come throws
nel metodo o almeno ritoccalo come new FacesException(e)
.
Aggiornare Secondo i commenti, non ti interessano affatto al servlet. Ecco un minore riscrivere come è possibile inviare a livello di programmazione il file Excel in un metodo di azione JSF.
public void getReportData() throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(0.0);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/vnd.ms-excel");
externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"my.xls\"");
workbook.write(externalContext.getResponseOutputStream());
facesContext.responseComplete();
}
Altri suggerimenti
Here is the that i wrote before and working case ;
xhtml ;
<h:panelGrid id="viewCommand" style="float:right;" >
<p:commandButton value="Export Excel" icon="ui-icon-document"
ajax="false" actionListener="#{xxx.export2Excel}"
rendered="#{xxx.showTable}">
<p:fileDownload value="#{xxx.exportFile}"
contentDisposition="attachment" />
</p:commandButton></h:panelGrid>
Java side(with POI) ;
protected void lOBExport2Excel(List table) throws Throwable {
Row row = null;
Cell cell = null;
try {
Workbook wb = new HSSFWorkbook();
HSSFCellStyle styleHeader = (HSSFCellStyle) wb.createCellStyle();
HSSFFont fontHeader = (HSSFFont) wb.createFont();
fontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
styleHeader.setFont(fontHeader);
Sheet sheet = wb.createSheet("sheet");
row = sheet.createRow((short) 0);
for (int i = 0; i < columnNames.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(columnNames.get(i));
cell.setCellStyle(styleHeader);
}
int j = 1;
for (DBData[] temp : tabularData) {
row = sheet.createRow((short) j);
for (int k = 0; k < temp.length; k++) {
HSSFCellStyle styleRow = (HSSFCellStyle) wb.createCellStyle();
HSSFFont fontRow = (HSSFFont) wb.createFont();
fontRow.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
styleRow.setFont(fontRow);
cell = row.createCell(k);
setStyleFormat(temp[k].getDataType(), styleRow, wb);
cell.setCellValue(temp[k].toFullString());
cell.setCellStyle(styleRow);
}
j++;
}
String excelFileName = getFileName("xls");
FileOutputStream fos = new FileOutputStream(excelFileName);
wb.write(fos);
fos.flush();
fos.close();
InputStream stream = new BufferedInputStream(new FileInputStream(excelFileName));
exportFile = new DefaultStreamedContent(stream, "application/xls", excelFileName);
} catch (Exception e) {
catchError(e);
}
}
I'd also recommend looking at using the PrimeFaces FileDownload. Depending on your structure it could make this all a whole lot easier. You wouldn't have to create a servlet just a managed bean that can provide a ContentStream
.
Since you already have the servlet written though, there's no point to change, just food for thought.