熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Struts2利用stream直接輸出Excel

2013-11-23 20:42:09  來源: Java開源技術 

  用網頁展示查詢結果經常會遇到要求導出成Excel的需求采用這種方法可以定制輸出的格式和內容(還不支持合並單元格和公式)生成真正的Excel格式(不是csv)的Excelstrutsxml <?xml version= encoding=UTF?> <!DOCTYPE struts PUBLIC     //Apache Software Foundation//DTD Struts Configuration //EN     dtd>    <struts>
        <constant name=strutsinencoding value=UTF/>

  <package name=demo extends=strutsdefault>         <action name=excel method=execute class=demoExcelAction>                 <result name=excel type=stream>                     <param name=contentType>application/vndmsexcel</param>    <! 注意這裡的ContentType >                     <param name=inputName>excelStream</param>                   <! 這裡需要和Action裡的變量名一致 >                     <param name=contentDisposition>filename=standardxls</param>                     <param name=bufferSize></param>                 </result>         </action>     </package> </struts>

  二Struts的 Action

  package demo; public class ExcelAction {     private InputStream excelStream; // 需要生成getter和setter

  public String execute() throws Exception {         StringBuffer excelBuf = new StringBuffer();         excelBufappend(BookName)append(\t)append(Year)append(\t)append(author)append(\n);         excelBufappend(Thinking in Java)append(\t)append()append(\t)append(Eckel)append(\n);         excelBufappend(Spring in action)append(\t)append()append(\t)append(Rod)append(\n);         String excelString = excelBuftoString();         loggerdebug(result excel String: + excelString);         excelStream = new ByteArrayInputStream(excelStringgetBytes() excelStringlength());         return excel;     }

  // getter and setter     }

  三Jsp頁面

  <%@ taglib prefix=s uri=/strutstags%> <!DOCTYPE HTML PUBLIC //WC//DTD HTML Transitional//EN> <html>  <head>   <s:head />  </head>

  <body>

  <s:form action= method=post>        <s:submit key=buttonsubmit/>     </s:form>  </body> </html>


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28923.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.