struts2自带excel导出功能
struts2中有对导出excel表格的支持,所以开发起来比较容易,主要的步骤有三点:
1.struts.xml的action相关配置:
<action name="ExportAction" type="stream"> <!-- 注意这里的ContentType --> <param name="contentType">application/vnd.ms-excel</param> <!-- 这里需要和Action里的变量名一致 --> <param name="inputName">excelStream</param> <param name="contentDisposition">filename="export.xls"</param> <param name="bufferSize">1024</param> </result> </action>
public class ExportAction extends ActionSupport { private QueryDao dao = new QueryDao(); private InputStream excelStream; public InputStream getExcelStream() { return excelStream; } public void setExcelStream(InputStream excelStream) { this.excelStream = excelStream; } @Override public String execute() throws Exception { StringBuffer excelBuf = new StringBuffer(); excelBuf.append("编号").append("\t").append("国家").append("\t").append("\n"); List<Country> list1 = dao.getCountryData(); for (int i = 0; i < list1.size(); i++) { Country country = (Country) list1.get(i); excelBuf.append(country.getId()).append("\t") .append(country.getName()).append("\t") .append("\n"); } String excelString = excelBuf.toString(); excelStream = new ByteArrayInputStream(excelString.getBytes(), 0, excelString.length()); return "excel"; } } <form action="<%=path %>/ExportAction.action" enctype="MULTIPART/FORM-DATA" method="post"> <input type="submit" value="导出excel"> </form>