9 Replies Latest reply on Aug 12, 2010 8:21 AM by yshashidhar

    Download Excel file from Seam component...

    yshashidhar

      Hi


      I have a requirement where in I need to give functionality to user for downloading excel file from server.
      I was walking through various posts over here, but my issue is not resolved... Please see below what I have done..


      xhtml code:
      <s:link id="slinkexportxls" value="Download" action="#{qualityIP.exportExcel}">
      </s:link>



      And here is my exportExcel method:
      createExcel();
                     
                       HttpServletResponse httpResponse =
                               (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
                       System.out.println("injected extCtx, httpoutput buffersize= - " + httpResponse.getBufferSize());
                      
                       File fFile = new File("D:\\Shashi\\ExportInspectionPlanToExcel.xls");
                       String stFileName = "ExportInspectionPlanToExcel.xls";
                      
                       httpResponse.setHeader ("Content-Disposition","attachment;filename=\""+stFileName+"\"");
                      
                       //the content type set as excel
                       httpResponse.setContentType("application/vnd.ms-excel");
                      
                       System.out.println("ExportInspectionPlanToExcel: Set all return properties...");
                       
                       //Open an input stream to the file and post the file contents thru the
                       //servlet output stream to the client m/c
                       InputStream isStream = null;
                       ServletOutputStream sosStream = null;
                       try {
                               //response.flushBuffer();
                               isStream = new FileInputStream(fFile);
                               sosStream = httpResponse.getOutputStream();
                               int ibit = 256;
                               while ((ibit) >= 0){
                                       ibit = isStream.read();
                                       sosStream.write(ibit);
                               }
                               System.out.println("ExportInspectionPlanToExcel: Done, closing all open streams...");
                               sosStream.flush();
                               System.out.println("Flushed, closing sos...");
                               sosStream.close();
                      
                       } catch (IOException exp){
                               System.out.println("exception -" +exp.getStackTrace());
                       }
                       FacesContext.getCurrentInstance().responseComplete();


      And that's it I have done... when I ran the above application... I don't see exportExcel method getting called after clicking Download Seam link


      Can any help please me where did I made mistake?


        • 1. Re: Download Excel file from Seam component...
          yshashidhar

          Sorry improper format in above post...
          Here is my exportExcel method -


                         createExcel();
                          
                           HttpServletResponse httpResponse = 
                                   (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
                           System.out.println("injected extCtx, httpoutput buffersize= - " + httpResponse.getBufferSize());
                           
                           File fFile = new File("D:\\Shashi\\ExportInspectionPlanToExcel.xls"); 
                           String stFileName = "ExportInspectionPlanToExcel.xls";
                           
                           httpResponse.setHeader ("Content-Disposition","attachment;filename=\""+stFileName+"\"");
                           
                           //the content type set as excel 
                           httpResponse.setContentType("application/vnd.ms-excel");
                           
                           System.out.println("ExportInspectionPlanToExcel: Set all return properties...");
                            
                           //Open an input stream to the file and post the file contents thru the 
                           //servlet output stream to the client m/c 
                           InputStream isStream = null; 
                           ServletOutputStream sosStream = null; 
                           try {
                                   //response.flushBuffer(); 
                                   isStream = new FileInputStream(fFile);
                                   sosStream = httpResponse.getOutputStream(); 
                                   int ibit = 256; 
                                   while ((ibit) >= 0){ 
                                           ibit = isStream.read(); 
                                           sosStream.write(ibit); 
                                   }
                                   System.out.println("ExportInspectionPlanToExcel: Done, closing all open streams...");
                                   sosStream.flush();
                                   System.out.println("Flushed, closing sos...");
                                   sosStream.close();
                           
                           } catch (IOException exp){ 
                                   System.out.println("exception -" +exp.getStackTrace()); 
                           }
          FacesContext.getCurrentInstance().responseComplete();
          



          And here is my xhtml piece of code


          <s:link id="slinkexportxls" value="Download" action="#{qualityIP.exportExcel}">
          </s:link>

          • 2. Re: Download Excel file from Seam component...
            yshashidhar

            Any one reply me please.
            It's bit urgent to me

            • 3. Re: Download Excel file from Seam component...
              pbrewer_uk

              Your code looks fine to me - I can't spot any obvious reason for it failing. I suppose a JSF validator doesn't prevent submission? You can check this by adding a h:messages component (and making sure it is reRendered or the page refreshed).


              If it helps, this is code that I've used before that works:


              DownloadBean.java


              import org.jboss.seam.document.ByteArrayDocumentData;
              
              ...
              
                public void download() {
                  download(generateData(), "attachment") ;
                }
              
                private ByteArrayDocumentData generateData() {
                  return new ByteArrayDocumentData(...) ;
                }
              
                private boolean download(ByteArrayDocumentData data, String disposition) {
              
                  if (data == null) {
                    return false;
                  }
                  
                  try {
                    FacesContext facesContext = FacesContext.getCurrentInstance() ;
                    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse() ;
              
                    String downloadFilename = data.getFileName() ;   
                    response.setContentType( data.getDocumentType().getMimeType() );
                    if (downloadFilename != null ) {
                      response.setHeader("Content-disposition", disposition + "; filename=\"" + downloadFilename + "\"");
                    }
                    OutputStream out = response.getOutputStream();
                    data.writeDataToStream(out) ;
                    response.flushBuffer() ;
                    facesContext.responseComplete();
                    return true ;
                  } catch(Exception ex) {
                    LOG.error("Error downloading report #0", ex, getReportViewId()) ;
                    return false ;
                  }    
                }



              download.xhtml


              <h:commandButton actionListener="#{downloadBean.download}" value="#{messages.downloadExport}" />

              • 4. Re: Download Excel file from Seam component...
                yshashidhar

                Okay... This time I changed my design slightly... Unfortunately I didn't the excel exported, but there are no errors in console...


                My xhtml code:


                <h:form id="qualityIPlanForm" style="width: 954px; height: 409px" enctype="multipart/form-data">
                ...
                <a4j:commandButton value='Download' action="#{qualityIP.exportExcel}"/>
                



                And here is my exportExcel (Modified version)


                          createExcel();
                          
                           HttpServletResponse httpResponse = 
                                (HttpServletResponse)facesContext.getExternalContext().getResponse();
                           
                           File fFile = new File("D:\\Shashi\\ExportInspectionPlanToExcel.xls"); 
                           String stFileName = "ExportInspectionPlanToExcel.xls";
                           
                           httpResponse.setHeader ("Content-Disposition","attachment;filename=\""+stFileName+"\"");
                           
                           //the content type set as excel 
                           httpResponse.setContentType("application/vnd.ms-excel");
                           
                           System.out.println("ExportInspectionPlanToExcel: Set all return properties...");
                            
                           //Open an input stream to the file and post the file contents thru the 
                           //servlet output stream to the client m/c 
                           InputStream isStream = null; 
                           ServletOutputStream sosStream = null; 
                           try {
                                //response.flushBuffer(); 
                                isStream = new FileInputStream(fFile);
                                sosStream = httpResponse.getOutputStream(); 
                                int ibit = 256; 
                                while ((ibit) >= 0){ 
                                     ibit = isStream.read(); 
                                     sosStream.write(ibit); 
                                }
                                System.out.println("ExportInspectionPlanToExcel: response Complete, redirected...");
                                httpResponse.flushBuffer();
                                facesContext.responseComplete();
                                return "Success";
                           } catch (IOException exp){ 
                                System.out.println("exception -" +exp.getStackTrace());
                                return "Failed";
                           }
                



                My exportExcel method returns String, indicating Success/Fail of method execution... I hope this m8 not create any prob...


                Unfortunately in server console I see all system out messages... but on browser I don't see the excel downloading... :-(


                Any help please?

                • 5. Re: Download Excel file from Seam component...
                  pbrewer_uk

                  You could try changing your xhtml to the following, just to see if it works:


                  <h:commandButton value='Download' actionListener="#{qualityIP.exportExcel}"/>



                  I seem to remember it is a bit funny getting your setup to work properly.


                  Also, you may want to investigate the document store facility and <s:resource> tag that I think may be of use to you (I know very little about this though).

                  • 6. Re: Download Excel file from Seam component...
                    yshashidhar
                    Tried with h:commandButton, but the same situation... No error on console and nothing is happening at UI.
                    Instead, I can say everything is executing fine inside method I have written.... but in IE there is no download option coming


                    "I tried with <s:resource> it seems the tag has no definition in xmlns defined at here "

                    `<s:resource xmlns="http://www.w3.org/1999/xhtml"

                        xmlns:s="http://jboss.com/products/seam/taglib"

                        data="#{resources.data}"

                        contentType="#{resources.contentType}"

                        fileName="#{resources.fileName}" />

                    `

                    Any help is really appreciated...""
                    • 7. Re: Download Excel file from Seam component...
                      pbrewer_uk

                      What version of Seam are you using? s:resource wasn't available until 2.1.2. Also don't forget to configure the web.xml as the documentation suggests.


                      As a side-note, your first post said you used



                      <s:link id="slinkexportxls" value="Download" action="#{qualityIP.exportExcel}">
                      </s:link>

                      So you should not need to add the xml namespace again - it should already be defined (i.e. remove xmlns:s and xmlns attributes from s:resource if it already appears further up the page), I don't think that would cause any problems though, its just more tidy.


                      • 8. Re: Download Excel file from Seam component...
                        yshashidhar

                        I am using Seam 2.0... so I think i can use s:resource functionality.



                                                           <s:link id="slinkexportxls" value="Download" action="#{qualityIP.exportExcel}">
                                                           </s:link>
                                                           <rich:spacer width="2px"/>
                                                           <a4j:commandButton action="#{qualityIP.exportExcel}" value="" 
                                                                image="/img/images/imgIconExcel_16x16.gif"
                                                                style="vertical-align:middle; width: 16px;"/>
                                                           <rich:spacer width="2px"/>
                        




                        1 First I tried with s:link and see the function itself calling which is defined inside method...


                        Here is the code for the same


                                                           <s:link id="slinkexportxls" value="Download" action="#{qualityIP.exportExcel}">
                                                           </s:link>
                        



                        in this case exportExcel itself is not calling...


                        2 In second shot, I am making use of command button as shown above. This time it executes complete exportExcel method shown below


                                   HttpServletResponse httpResponse = 
                                        (HttpServletResponse)facesContext.getExternalContext().getResponse();
                                   
                                   File fFile = new File("D:\\Shashi\\ExportInspectionPlanToExcel.xls"); 
                                   String stFileName = "ExportInspectionPlanToExcel.xls";
                                   
                                   httpResponse.setHeader ("Content-Disposition","attachment;filename=\""+stFileName+"\"");
                                   
                                   //the content type set as excel 
                                   httpResponse.setContentType("application/vnd.ms-excel");
                                   
                                   System.out.println("ExportInspectionPlanToExcel: Set all return properties...");
                                    
                                   //Open an input stream to the file and post the file contents thru the 
                                   //servlet output stream to the client m/c 
                                   InputStream isStream = null; 
                                   ServletOutputStream sosStream = null; 
                                   try {
                                        //response.flushBuffer(); 
                                        isStream = new FileInputStream(fFile);
                                        sosStream = httpResponse.getOutputStream(); 
                                        int ibit = 256; 
                                        while ((ibit) >= 0){ 
                                             ibit = isStream.read(); 
                                             sosStream.write(ibit); 
                                        }
                                        isStream.close();
                                        sosStream.flush();
                                        System.out.println("ExportInspectionPlanToExcel: response Complete, redirected...");
                                        
                                        httpResponse.flushBuffer();
                                        facesContext.responseComplete();
                                        facesContext.renderResponse();
                                        return "Success";
                                   } catch (IOException exp){ 
                                        System.out.println("exception -" +exp.getStackTrace());
                                        return "Failed";
                                   }
                        



                        Even I see all system out messages. But in browser I don't see the file getting downloaded...



                        • 9. Re: Download Excel file from Seam component...
                          yshashidhar

                          Sorry typo..
                          my say in previous post I think i can use s:resource functionality
                          should have been I think i can't use s:resource functionality


                          btw, should I need to do anything on server to respond for downloads?