struts2中有对导出excel表格的支持,所以开发起来比较容易,主要的步骤有三点:
1.struts.xml的action相关配置:
<action name="ExportAction" class="com.huawei.nsm.workflow.action.ExportAction">
<result name="excel" 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>
2.JAVA的ExportAction类:
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";
}
}
3.页面提交:
<form action="<%=path %>/ExportAction.action" enctype="MULTIPART/FORM-DATA" method="post">
<input type="submit" value="导出excel">
</form>
以上就是struts2自带的excel导出功能.其实如果想使导出的excel变得更漂亮,就使用apache的poi包,有以下几类:
poi-3.7-20101029.jar
poi-ooxml-3.7-20101029.jar
poi-ooxml-schemas-3.7-20101029.jar,
poi-scratchpad-3.7-20101029.jar