質問

JDK 1.6、JSF 2.1、PrimeFaces 2.2.1、POI 3.2、およびApache Tomcat 7の使用

ユーザーの選択に基づいてExcelファイルをダウンロードできるようにサーブレットをセットアップしようとしています。 Excelドキュメントは実行時に作成されます。

エラーはなく、コードはサーブレットに入ります。

ボタンをクリックすると何も起こりません。 Excelドキュメントのデータの並べ替えとカスタムフォーマットを行う必要があるため、PrimeFacesが使用するデータテーブルエクスポートを使用していません。

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>
役に立ちましたか?

解決

2つの問題があります。

最初の問題は、です <p:commandButton> デフォルトでAJAXリクエストを送信します。このリクエストは、JavaScriptコードによって起動されます。ただし、JavaScriptは、ファイルのダウンロードを含む応答で何もできません。セキュリティの制限により、JavaScriptはスポーンできません ASを保存します 対話か何か。応答は基本的に完全に無視されます。

追加する必要があります ajax="false"<p:commandButton> ボタンが通常の同期HTTPリクエストを発射するようにAJAXをオフにするか、標準に置き換える必要があります <h:commandButton>.

<p:commandButton ajax="false" ... />

また

<h:commandButton ... />

2番目の問題は、サーブレットがExcelファイルを応答にまったく記述せず、代わりにサーバーのワーキングディレクトリに保存されているローカルファイルに書き込むことです。基本的に、HTTP応答には含まれています なし. 。あなたは合格する必要があります HttpServletResponse#getOutputStream()WorkBook#write() 方法。

workbook.write(response.getOutputStream());

無関係なメモでは、ここでサーブレットがどのように役立つのだろうかと思います。 JSFの外で再利用しますか?そうでない場合は、必ずしもサーブレットにディスパッチする必要はありませんが、Beanのアクションメソッドで同じコードを実行するだけです。その空 catch ブロックも良くありません。私はちょうどそれを宣言します throws 方法で、または少なくともそれを蘇らせます new FacesException(e).


アップデート コメントに従って、あなたはサーブレットにまったく興味がないようです。 JSFアクションメソッドでプログラムでExcelファイルを送信する方法をマイナーに書き直します。

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();
}

他のヒント

これが私が以前に書いたことと仕事のケースです。

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側(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);
    }

}

また、PrimeFaces FileDownLoadの使用を検討することをお勧めします。構造に応じて、これをずっと簡単にすることができます。サーブレットを作成する必要はありません。 ContentStream.

あなたはすでにサーブレットを書いているので、変化する意味はありません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top