下载在Java Web应用程序中创建的.xls文件

时间:2017-07-04 15:44:41

标签: jsf download

我使用POI API创建了.xls文件。 现在我想向用户显示对话框,以选择下载文件的位置,以便我搜索并找到下面的代码块,但它不会使任何内容既不显示对话框也不下载文件。

我的豆子:

@ManagedBean(name = "usersBulkUploadBean")
@ViewScoped
public class UsersBulkUploadBean {

    private static final String BEAN_NAME = "UsersBulkUploadBean";
    private static final long serialVersionUID = 1L;
    private HttpSession session;
    private MainService mainService;
    private UploadedFile file;
    private Map<HSSFRow, String> failedUsers; 
    private ShortUserModel shortUserModel;

    @ManagedProperty(value = "#{customerInfoBean}")
    private UsersListBean userListBean;

    public String downloadUsersSheet() { 
        CommonLogger.debugLogger.debug("[" + shortUserModel.getId() + "]:"
            + BEAN_NAME + ":downloadUsersSheet:started.");
        String retPage = "UsersBulkUpload.xhtml?faces-redirect=true";
        Date stepStartDate = new Date();

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();

        // Download Process
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Users");
            HSSFRow row;
            HSSFCell cell;
            int columnCount;
            int rowCount = 0;

            sheet = getUserListBean().createExcelHeader(sheet);

            for (Map.Entry<HSSFRow, String> failedRow : failedUsers.entrySet()) {
                HSSFRow failedUser = failedRow.getKey();
                columnCount = 0;
                row = sheet.createRow(++rowCount);

                if (failedUser.getCell(1) == null) continue;

                cell = row.createCell(columnCount);
                double userId = failedUser.getCell(columnCount).getNumericCellValue();
                cell.setCellValue(userId);
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);

                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);
                cell.setCellValue(failedUser.getCell(columnCount) != null ? 
                failedUser.getCell(columnCount).getStringCellValue() : null);
                sheet.autoSizeColumn(columnCount++);

                String languageChar = failedUser.getCell(columnCount).getStringCellValue();
                cell = row.createCell(columnCount);
                cell.setCellValue(languageChar);
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);
                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);
                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);
                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);

                cell = row.createCell(columnCount);
                cell.setCellValue(failedUser. getCell(columnCount).getStringCellValue());
                sheet.autoSizeColumn(columnCount++);
            }

            // Add all Lists in Excel sheet
            sheet = getUserListBean().addAllListsToExcelSheet(sheet);

            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            externalContext.responseReset();
            externalContext.setResponseContentType("application/vnd.ms-excel");
            String filename = "Failed_Users_"+ dateFormat.format(date).toString() + ".xls";
            externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

            workbook.write(externalContext.getResponseOutputStream());
            facesContext.responseComplete();

        } catch (Exception e) {
            e.printStackTrace();
            CommonLogger.errorLogger.error(BEAN_NAME
                + ":downloadUsersSheet:Exception, " + e.getMessage(), e);

            FacesMessage curMessage;
            if (failedUsers == null)
                curMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, ErrorMessages.MISSING_UPLOAD_FILE, null);
            else if (failedUsers.size() != 0)
                curMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, ErrorMessages.FAILED_USERS_DOWNLOAD_ERROR, null);
        else 
                curMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, ErrorMessages.NO_FAILED_USERS_TO_DOWNLOAD, null);

            FacesContext.getCurrentInstance().addMessage(null, curMessage);
            retPage = null;
        }

        // End Download Process

        Date stepEndDate = new Date();
        long totalProcessingTime = stepEndDate.getTime()
            - stepStartDate.getTime();
        CommonLogger.debugLogger.debug("[" + shortUserModel.getId() + "]:"
            + BEAN_NAME + ":downloadUsersSheet:ended in "
            + totalProcessingTime + " msec");
        return retPage;
    }
}

我的页面:

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
template="/Template/menuTempplate.xhtml">


<ui:define name="content">

    <f:metadata>
        <f:viewAction action="#{usersBulkUploadBean.init()}" />
    </f:metadata>

    <h:form>
        <div id="Messages" align="center">
            <p:messages id="msgs" showDetail="false" autoUpdate="true"
                closable="true" />
        </div>
        <div class="table_title_text">
            <p:panelGrid columns="1" style="width:100%">
                <p:outputLabel value="#{msgs['page.title.UsersBulkUpload']}" />
            </p:panelGrid>
        </div>
        <div class="searchArea">
            <p:panelGrid columns="3" style="width:10%">                 
                <p:fileUpload mode="advanced" 
                              fileUploadListener="#{usersBulkUploadBean.uploadFile}" 
                              auto="true" 
                              allowTypes="/(\.|\/)(xls|xlsx)$/" 
                              multiple="false" 
                              skinSimple="true" 
                              lable="#{msgs['button.label.upload']}" />

                <p:commandButton styleClass="button" 
                                 ajax="false" 
                                 id="fade"
                                 value="#{msgs['button.label.download']}" 
                                 action="#{usersBulkUploadBean.downloadUsersSheet()}" />
            </p:panelGrid>
        </div>
    </h:form>
</ui:define>

上传部分正在运行,但下载没有显示上面提到的对话框。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

谢谢-1 :(

我设法找到了它。下面的代码与我合作

.not(':button, :submit, :reset, form:hidden')