用网页展示查询结果经常会遇到要求导出成Excel的需求采用这种方法可以定制输出的格式和内容(还不支持合并单元格和公式)生成真正的Excel格式(不是csv)的Excel一strutsxml <?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>