Export to Excel JSF and PrimeFaces

前端 未结 3 1955
梦毁少年i
梦毁少年i 2020-12-01 11:08

Using JDK 1.6, JSF 2.1, PrimeFaces 2.2.1, POI 3.2, and Apache Tomcat 7

I am trying to setup a servlet to allow a download of an excel file based on the user selectio

3条回答
  •  清歌不尽
    2020-12-01 11:56

    Here is the that i wrote before and working case ;

    xhtml ;

    
                            
                                
                            
    

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

提交回复
热议问题