public ActionForward exportExcel(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
String sfile = this.getServlet().getServletContext().getRealPath("/upload/")+ File.separator +"data.xls";// 服务器端名字
String filename ="data.xls";// 客户端名字
OutputStream os = null;
WritableWorkbook wwb = null;
try {
os = new FileOutputStream(savePath);
wwb = Workbook.createWorkbook(os);//第一步,创建一个webbook,对应一个Excel文件
WritableSheet ws = wwb.createSheet("statistics", 0); //第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
for (int i = 0; i < titleList.size(); i++) {
String title = (String) titleList.get(i);
Label titleLabel = new Label(i+1, 0, title);//从第二列 第一行 开始
ws.addCell(titleLabel);
}
for (int i = 0; i < dataList.size(); i++) {
Map obj= (HashMap) dataList.get(i);
String areaName = (String) obj.get("时间");//价格
Label areaNameLabel = new Label(0, i+1, areaName);
ws.addCell(areaNameLabel);//第一行的值
for (int k = 0; k < str.length; k++) {
if(db != null&& db.trim().equals("0")&&i>2){
Label label = new Label(1+(k*3), i + 1, "xxx");
ws.addCell(label);
label = new Label(2+(k*3), i + 1, "xxx");
ws.addCell(label);
label = new Label(3+(k*3), i + 1, "xxx");
ws.addCell(label);
}else{
String number = (String) obj.get(str[k][0] + "n");//数量
String sum = (String) obj.get(str[k][0] + "s");//金额
String cif = (String) obj.get(str[k][0] + "c");//价格
Label label = new Label(1+(k*3), i + 1, number==null?"0":number);
ws.addCell(label);
label = new Label(2+(k*3), i + 1, sum==null?"0":sum);
ws.addCell(label);
label = new Label(3+(k*3), i + 1, cif==null?"0":cif);
ws.addCell(label);
}
}
}
wwb.write();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
wwb.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
response.setContentType("application/vnd.ms-excel");
BufferedOutputStream out = new BufferedOutputStream(
new DataOutputStream(response.getOutputStream()));
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(sfile));
byte[] b = new byte[in.available()];
in.read(b);
out.write(b);
out.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}