---
title: "Struts2利用stream直接输出Excel"
author: "chunpeng"
date: "2008-11-10T20:23:46Z"
tags: ["Apache", "Excel", "Spring", "Struts", "XML"]
slug: "struts2-stream-excel"
draft: false
lastmod: "2008-11-10T20:23:46Z"
id: 265222
url: "https://chunpeng.iteye.com/blog/265222"
---

在利用网页展示查询结果，经常会遇到要求导出成Excel的需求。采用这种方法可以定制输出的格式和内容（还不支持合并单元格和公式），生成真正的Excel格式（不是csv）的Excel。  
一、struts.xml  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;  
    
&lt;struts&gt;

    &lt;constant name="struts.i18n.encoding" value="UTF-8"/&gt;

    &lt;package name="demo" extends="struts-default"&gt;  
        &lt;action name="excel" method="execute" class="demo.ExcelAction"&gt;  
                &lt;result name="excel" type="stream"&gt;  
                    &lt;param name="contentType"&gt;application/vnd.ms-excel&lt;/param&gt;    &lt;!-- 注意这里的ContentType --&gt;  
                    &lt;param name="inputName"&gt;excelStream&lt;/param&gt;                   &lt;!-- 这里需要和Action里的变量名一致 --&gt;  
                    &lt;param name="contentDisposition"&gt;filename="standard.xls"&lt;/param&gt;  
                    &lt;param name="bufferSize"&gt;1024&lt;/param&gt;  
                &lt;/result&gt;  
        &lt;/action&gt;  
    &lt;/package&gt;  
&lt;/struts&gt;

二、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页面

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

 &lt;body&gt;

    &lt;s:form action="" method="post"&gt;  
       &lt;s:submit key="button.submit"/&gt;  
    &lt;/s:form&gt;  
 &lt;/body&gt;  
&lt;/html&gt;