继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

struts2: 通过流输出实现exce导出

慕尼黑的夜晚无繁华
关注TA
已关注
手记 234
粉丝 60
获赞 316

参考下面代码,在Action中加一个方法:

复制代码

 1     // 导出excel 
 2     public String excel() throws Exception { 
 3     StringBuffer excelBuf = new StringBuffer(); 
 4     excelBuf.append("运单号").append("\t").append("始发站").append("\t").append("目的站").append("\n"); 
 5     excelBuf.append("112-00100100").append("\t").append("PEK").append("\t").append("SHA").append("\n"); 
 6     excelBuf.append("112-00100111").append("\t").append("PVG").append("\t").append("XIY").append("\n"); 
 7     excelBuf.append("112-00100122").append("\t").append("SHA").append("\t").append("HHY").append("\n"); 
 8     String excelString = excelBuf.toString(); 
 9     excelStream = new ByteArrayInputStream(excelString.getBytes(), 0, excelString.getBytes().length);
 10     return "excel";
 11     }

复制代码

实质上是一个格式化的cvs文本文件,但是所有的excel/wps都能识别这种格式,导出的数据量不大,且没有复杂的线框格式要求时,这种处理方式最为方便

 

struts2的配置文件:

复制代码

 1 <package name="cba_index" ...> 
 2     ... 
 3     <action name="index_*" method="{1}" class="CbaAction"> 
 4         <result name="success">/mu-reservation/cba/index.jsp</result>             
 5         <!-- 导出excel --> 
 6         <result name="excel" type="stream"> 
 7             <param name="contentType">application/vnd.ms-excel</param>    <!-- 注意这里的ContentType --> 
 8             <param name="inputName">excelStream</param>                   <!-- 这里需要和Action里的变量名一致 --> 
 9             <param name="contentDisposition">filename="download.xls"</param> <!-- 下载文件的名字 -->
 10             <param name="bufferSize">10240</param>  <!-- 下载文件的大小 10485760=10M -->
 11         </result>
 12     </action>
 13     ...
 14 </package>

复制代码

页面上

1 <a href="index_excel.do" target="_blank">导出excel示例</a>

导出后的文件打开效果:


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP