struts2中有对导出excel表格的支持,所以开发起来比较容易,主要的步骤有三点:
1.配置文件:
<action name="excel" class="userAction" method="excel" >
<result name="excel" type="stream">
<!-- 注意这里的ContentType -->
<param name="contentType">application/vnd.ms-excel</param>
<!-- 这里需要和Action里的变量名一致 -->
<param name="inputName">excelStream</param>
<param name="contentDisposition">filename="user.xls"</param>
<param name="bufferSize">1024</param>
</result>
</action>
2.action中的函数为excel如下:
public String excel() throws Exception {
StringBuffer excelBuf = new StringBuffer();
excelBuf.append("编号").append("\t").append("登录名称").append("\t").append("联系人").append("\t").append("电话").append("\t").append("Email").append("\t").append("所属单位").append("\n");
List list1 = mobjUserService.findAllUser();
for (int i = 0; i < list1.size(); i++) {
User user = (User) list1.get(i);
excelBuf.append(user.getUserId()).append("\t").append(user.getLoginName()).append("\t").append(user.getContactPerson()).append("\t").append(user.getPhone()).append("\t").append(user.getEmail()).append("\t").append(user.getRecommendCompany().getCompanyName()).append("\n");
}
//excelBuf.append("Thinking in Java").append("\t").append("2001").append("\t").append("Eckel").append("\n");
//excelBuf.append("Spring in action").append("\t").append("2005").append("\t").append("Rod").append("\n");
String excelString = excelBuf.toString();
//logger.debug("result excel String: " + excelString);
excelStream = new ByteArrayInputStream(excelString.getBytes(), 0, excelString.length());
return "excel";
}
3.jsp中对应:
<td width="10%">
<input name="Submit" type="button" class="button"
onClick="javaScript:sysReturn('<c:out value="${ctx}"/>/excel.action');"
value="<s:text name="导出excel"/>">
</td>
比较简单好用就不详细描述了。