cndavy

导航

 

 1、近期使用primeface 做项目遇到了问题,不断的解决问题.下面是导出excel的部分代码

  <p:commandButton value="项目下载(EXCEL)"           immediate="true"
                             update=":formprocess:panelprocess" 

                                   actionListener="#{projectManageAction.ExcelReport}"  ajax="false" >
                <p:fileDownload value="#{projectManageAction.excelFile}" />
            </p:commandButton>

在后台projectManageAction

 public StreamedContent getExcelFile() {
        return excelFile;
    }
private StreamedContent excelFile;

起初使用 response.OutputStream 会出现错误,虽然也能够下载,但是毕竟不美观,既然使用primeface 就彻底些,使用      <p:fileDownload value="#{projectManageAction.excelFile}" />
来下载excel文件

 
  public void ExcelReport() {
        if (selectProject==null ||selectProject.getProjectitemnum()==nullreturn;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {

            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
          //  response.reset();
            String fileName = "ProjectDetail.xls";
         //   response.setHeader("Content-disposition", "attachment; filename=" + fileName);
         
//   response.setContentType("application/msexcel");
            
//模板

            String operid = SystemService.getOperatorManager().getOperatorId();
            Map beans = new HashMap();
            beans.put("operid",operid);
            beans.put("sdf",sdf)  ;

            DatabaseConnection conn = ConnectionManager.getInstance().get();
            beans.put("projectitem",this.selectProject.getProjectitemnum())   ;
            beans.put("project",crService.selectProjectByPK(this.selectProject.getProjectitemnum()));
            ReportManager reportManager = new ReportManagerImpl(conn.getConnection(), beans);
            beans.put("rm", reportManager);
            XLSTransformer transformer = new XLSTransformer();
           InputStream is = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream("/resources/crfs/" + "ProjectDetailModel.xls"));
            org.apache.poi.ss.usermodel.Workbook wb = transformer.transformXLS(is, beans);
            is.close();

            //OutputStream os = response.getOutputStream();

//在把outputsteam 转换为intputsteam 不能使用 pipe,可能buff太小,调试的时候挂在那里了。于是改用bytearray


           ByteArrayOutputStream os= new  ByteArrayOutputStream();
            wb.write(os);os.flush();
            byte[] buff = os.toByteArray();
            ByteArrayInputStream stream=new ByteArrayInputStream(buff);

            os.close();

            excelFile  = new DefaultStreamedContent(stream, "application/vnd.ms-excel",  "project-"+this.selectProject.getProjectitemnum()+".xls");


        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

            ConnectionManager.getInstance().release();

        }

    }

excel 模板中

<jx:forEach items = "${rm.exec("
select
processnum,processbranch,processstartdate,processenddate,
processprofile,processaudit,processeditor,  processproject
from process where processproject='"+projectitem+"'")}"
  var="process">  

 

${sdf.format(process.processstartdate)}

 

2、 上传excel的例子

 

 

<h:form enctype="multipart/form-data">

            <p:fileUpload fileUploadListener="#{projectManageAction.onAddProblemBatch}"
                          mode="advanced"
                          update=":inputform:msgs"
                          sizeLimit="100000"
                          showButtons="false"
                          uploadLabel="上传"
                          cancelLabel="取消"
                          label="浏览并上传项目文件(xls)"
                          allowTypes="/(\.|\/)(xlsx|xls)$/"/>
        </h:form>

 

View Code
 1   public       String  onAddProblemBatch(FileUploadEvent event){
 2            //TODO   excel import
 3         try{
 4            ;
 5             UploadedFile file = event.getFile();
 6             if (file != null)
 7             {
 8              InputStream inputStream= file.getInputstream();
 9                 {    //保存上传文件到指定目录    ,要是不想保存可以直接使用inputsteam
10                 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
11                 String modelPath = PropertyManager.getProperty("REPORT_ROOTPATH") ;
12                 int lastindex=  file.getFileName().lastIndexOf('\\');
13 
14                 modelPath=modelPath+file.getFileName().substring(lastindex+1,file.getFileName().length()) ;
15                 BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(modelPath));
16                 byte[] b1=new byte[(int) file.getSize()];
17                 bufferedInputStream.read(b1);
18 
19                 bufferedOutputStream.write(b1);
20 
21                 bufferedInputStream.close();
22                 bufferedOutputStream.close();
23               }
24 
25                MessageUtil.addInfo(
26                         " 成功上传项目进度文件:" + file.getFileName() +
27                                 " (" + file.getSize() + " bytes)");
28 
29 
30             }
31 
32         }
33         catch (Exception e){
34             MessageUtil.addError("生成新问题出错" + e.getMessage());
35         }
36         return null;
37 
38     }

 

 

posted on 2012-03-23 15:06  cndavy  阅读(597)  评论(0编辑  收藏  举报