这里说下struts2导出Excel文件的列子。java
列子比较简单。下面是咱们导出Excel须要的jar包。web
struts2须要jar包:commons-logging.jar、freemarker-2.3.8.jar、ognl-2.6.11.jar、struts2-core-2.0.11.1.jar、xwork-2.0.4.jarapache
excel导出:jxl.jarapp
下面为配置web.xml的内容:ide
..... <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ......
下面为struts2的配置文件代码[filename为导出时弹出来的名称]:url
<?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> <package name="platform-default" extends="struts-default"> <action name="excel" class="action.ExcelAction"> <result name="excel" type="stream"> <param name="contentType"> application/vnd.ms-excel </param> <param name="inputName">excelStream</param> <param name="contentDisposition"> filename="export.xls" </param> <param name="bufferSize">1024</param> </result> </action> </package> </struts>
Action的代码:spa
package action; import java.io.InputStream; import service.IExcelService; import service.impl.ExcelServiceImpl; public class ExcelAction { InputStream excelStream; public String execute(){ IExcelService es = new ExcelServiceImpl(); excelStream = es.getExcelInputStream(); return "excel"; } //get set... }
Service的接口代码:excel
package service; import java.io.InputStream; public interface IExcelService { InputStream getExcelInputStream(); }
Service代码:code
package service.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import jxl.Workbook; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import service.IExcelService; public class ExcelServiceImpl implements IExcelService { @Override public InputStream getExcelInputStream() { //将OutputStream转化为InputStream ByteArrayOutputStream out = new ByteArrayOutputStream(); putDataOnOutputStream(out); return new ByteArrayInputStream(out.toByteArray()); } private void putDataOnOutputStream(OutputStream os) { jxl.write.Label label; WritableWorkbook workbook; try { workbook = Workbook.createWorkbook(os); WritableSheet sheet = workbook.createSheet("Sheet1", 0); label = new jxl.write.Label(0, 0, "struts2导出excel"); sheet.addCell(label); workbook.write(); workbook.close(); } catch (Exception e) { e.printStackTrace(); } } }
主要事项:例子中OutputStream转InputStream是一种简单的实现,可是须要内存比较多