java

位置:IT落伍者 >> java >> 浏览文章

Struts2利用stream直接输出Excel


发布日期:2019年11月08日
 
Struts2利用stream直接输出Excel

用网页展示查询结果经常会遇到要求导出成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>

上一篇:Spring 包结构

下一篇:Struts1.x系列教程(2):简单的数据验证