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>
转自:http://www.blogjava.net/usherlight/archive/2008/06/23/210135.html
发表评论
- 浏览: 2453 次
- 性别:

- 来自: 天津

- 详细资料
搜索本博客
最近加入圈子
链接
最新评论
-
开发者版本:你属于哪个版 ...
引用只要不乘100就好。。。 阁下是多少?
-- by hilliate -
开发者版本:你属于哪个版 ...
xiao0556 写道我大约属于2.5吧 只要不乘100就好。。。
-- by wangdi -
开发者版本:你属于哪个版 ...
我大约属于2.5吧
-- by xiao0556 -
开发者版本:你属于哪个版 ...
我想知道的是,每个级别的人应该拿多少钱合适?这是个问题,大家能否讨论下
-- by hilliate -
编程和足球的关系,给一些 ...
kevinsai 写道我现在有2个选择,一个正在工作的小公司,小公司里面的员工好 ...
-- by hilliate






评论排行榜