Struts2利用stream直接輸出Excel (轉)

Struts2利用stream直接輸出Excel (轉)

在利用網頁展示查詢結果,經常會遇到要求導出成Excel的需求。採用這種方法可以定製輸出的格式和內容(還不支持合併單元格和公式),生成真正的Excel格式(不是csv)的Excel。
一、struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
  
<struts>

    <constant name="struts.i18n.encoding" value="UTF-8"/>

    <package name="demo" extends="struts-default">
        <action name="excel" method="execute" class="demo.ExcelAction">
                <result name="excel" type="stream">
                    <param name="contentType">application/vnd.ms-excel</param>    <!-- 注意這裏的ContentType -->
                    <param name="inputName">excelStream</param>                   <!-- 這裏需要和Action裏的變量名一致 -->
                    <param name="contentDisposition">filename="standard.xls"</param>
                    <param name="bufferSize">1024</param>
                </result>
        </action>
    </package>
</struts>

二、Struts2的 Action

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

    public String execute() throws Exception {
        StringBuffer excelBuf = new StringBuffer();
        excelBuf.append("BookName").append("/t").append("Year").append("/t").append("author").append("/n");
        excelBuf.append("Thinking in Java").append("/t").append("2001").append("/t").append("Eckel").append("/n");
        excelBuf.append("Spring in action").append("/t").append("2005").append("/t").append("Rod").append("/n");
        String excelString = excelBuf.toString();
        logger.debug("result excel String: " + excelString);
        excelStream = new ByteArrayInputStream(excelString.getBytes(), 0, excelString.length());
        return "excel";
    }

    // getter and setter
    ...
}

三、Jsp頁面

<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <s:head />
 </head>

 <body>

    <s:form action="" method="post">
       <s:submit key="button.submit"/>
    </s:form>
 </body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章