日期:2014-05-19 浏览次数:20819 次
<action name="exportExcel" class="exportExcel">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param><!-- 下载文件类型 -->
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${filename}"</param><!-- 下载文件名 -->
<param name="bufferSize">1024</param>
</result>
</action>
public class ExportExcel extends BaseAction {
....
private InputStream inputStream;
private String filename;
getter&setter.....
public String exportExecl() {
response.reset();
response.setContentType("application/vn.ms-excel");
response.setCharacterEncoding("utf-8");
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.reset();
try {
WritableWorkbook book = Workbook.createWorkbook(os);
WritableSheet sheet = book.createSheet("第一页", 0);
int num = title.split(",").length;
for (int i = 0; i < num; i++) {
sheet.addCell(new Label(i, 0, title.split(",")[i]));
}
int xNumber = 1; // 定义循环的行的编号变量随for循环自动循环
List l = null;
l = tjService.query(sql);
if (l != null && l.size() > 0) {
System.out.println("size" + l.size());
String v[] = val.split(",");
for (int i = 0; i < l.size(); i++) {
clsObj = l.get(i);
for (int j = 0; j < v.length; j++) {
String methodname = "get" + v[j].substring(0, 1).toUpperCase() + v[j].substring(1);
Method method = clsObj.getClass().getMethod(methodname, new Class[] {});
Object o = method.invoke(clsObj, new Class[] {});
if (o == null) {
sheet.addCell(new Label(j, xNumber, ""));
} else {
sheet.addCell(new Label(j, xNumber, o.toString()));
}
}
++xNumber;
}
}
book.write();
book.close();
this.filename = new Date().toString() + ".xls";
this.inputStream = new ByteArrayInputStream(os.toByteArray());
} catch (Exception e) {
System.out.println("excel表格创建或写入错误,错误信息如下");
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
}