一个工程要动态生成excel报表是经常的事,一般情况下,生成的报表都是供用户查看或者下载,我们往往不需要将其生成到服务器的硬盘里,最好是生成到缓存里供本次调用,这时我们可以采用io流,代码如下:
public class Excel {
\**
* 把ArrayList<ArrayList>里的数据生成Excel文件.xls
* @param rowsList 结果集
* @param response 不生成文件,直接保存/打开
*\
public static void getExcel(ArrayList<ArrayList> rowsList,HttpServletResponse response) throws FileNotFoundException, IOException, RowsExceededException, writeException{
response.setContentType("application/ms-excel");
String sheetName = "11111.xls"; //Excel文件名称
// attachment; 这个代表要下载的,如果去掉就编程直接打开了
// filename是文件名,另存为或者下载时,为默认的文件名
response.addHeader("Content-Disposition", "attachment; filename="+sheetName);
java.io.OutputStream os = response.getOutputStream();
WritableWorkbook wwb = Workbook.createWorkbook(os);
jxl.write.WritableSheet ws = wwb.createSheet("22222", 0); // 创建Excel文件里的表单
Label labelC = null;
for(int j=0;j<rowsList.size();j++){ //循环记录数,即Excel中的行,因为有标题行,所以加1行
for(int k=0;k<rowsList.get(0).size();k++){ //循环每条记录的列
labelC = new Label(k, j, rowsList.get(j).get(k).toString()); //列数,行数,内容,字体样式可省略
ws.addCell(labelC);
}
}
if (wwb != null) {
wwb.write();
wwb.close();
}
}
}
这是我做程序的代码:
public String exportExcel() throws Exception{
response.setContentType("application/ms-excel");
String sheetName = "11111.xls";
response.addHeader("Content-Disposition", "attachment; filename="+sheetName);
// String realpath = ServletActionContext.getServletContext().getRealPath("/cache/supplier.xls");
// File file = new File(realpath);
// if(file.exists())
// file.delete();
OutputStream os = response.getOutputStream();
WritableWorkbook book = Workbook.createWorkbook(os);
WritableSheet sheet = book.createSheet("服务商信息", 0);
Label label;
Number number;
label = new Label(0, 0, "序号");
sheet.addCell(label);
label = new Label(1, 0, "公司名称");
sheet.addCell(label);
label = new Label(2, 0, "负责人");
sheet.addCell(label);
label = new Label(3, 0, "服务项目");
sheet.addCell(label);
label = new Label(4, 0, "服务区域");
sheet.addCell(label);
label = new Label(5, 0, "派单数");
sheet.addCell(label);
label = new Label(6, 0, "成单率");
sheet.addCell(label);
label = new Label(7, 0, "信誉级别");
sheet.addCell(label);
if(data==null){
data = new Supplier();
}
List<Supplier> list = supplierService.findExcel(data);
for(int i=0;i<list.size();i++){
number = new Number(0,i+1,i+1);
sheet.addCell(number);
label = new Label(1,i+1,list.get(i).getSupplierName());
sheet.addCell(label);
label = new Label(2,i+1,list.get(i).getResp());
sheet.addCell(label);
label = new Label(3,i+1,list.get(i).getServiceDes());
sheet.addCell(label);
label = new Label(4,i+1,list.get(i).getAreaDes());
sheet.addCell(label);
number = new Number(5,i+1,list.get(i).getCount());
sheet.addCell(number);
number = new Number(6,i+1,list.get(i).getRation());
sheet.addCell(number);
label = new Label(7,i+1,list.get(i).getCreditID());
sheet.addCell(label);
}
book.write();
book.close();
return null;
}
此方法使用的servlet默认方法,此外还有strut2的下载。有待研究
来源:https://www.cnblogs.com/hyteddy/archive/2011/07/21/2113165.html