工作中需要动态生成excel并提供下载,留在这个为了以后方面COPY。
protected void responseExcel(String filename,List<String> title,List<String> mapKey,List<Map<String, Object>> reportList,HttpServletResponse resp) throws Exception{
resp.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode("下载文件名.xls", "UTF-8"));// 设定输出文件头
resp.setContentType("application/msexcel");// 定义输出类型
resp.getOutputStream().flush(); //立刻弹出下载提示框
WritableWorkbook book = Workbook.createWorkbook(resp.getOutputStream());
WritableSheet wsheet = book.createSheet("sheet1", 0);
// 设置单元格的文字格式
WritableFont wf = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
WritableCellFormat wcf = new WritableCellFormat(wf);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
wcf.setAlignment(Alignment.CENTRE);
Label label = null;
for(int i=0;i<title.size();i++){
label = new Label(i, 0, title.get(i),wcf);
wsheet.addCell(label);
}
WritableCellFormat cf1 = new WritableCellFormat(new DateFormat("yyyy-MM-dd"));
WritableCellFormat cf2 = new WritableCellFormat(NumberFormats.INTEGER);
WritableCellFormat cf3 = new WritableCellFormat(NumberFormats.FLOAT);
Object value = null;
for(int i=0;i<reportList.size();i++){
for(int j=0;j<mapKey.size();j++){
value = reportList.get(i).get(mapKey.get(j));
if(value == null){
wsheet.addCell(new Label(j,i+1,""));
continue;
}
if(value instanceof Integer){
wsheet.addCell(new jxl.write.Number(j,i+1,(Integer)value,cf2));
}else if(value instanceof Float){
wsheet.addCell(new jxl.write.Number(j,i+1,(Float)value,cf3));
}else if(value instanceof Date){
wsheet.addCell(new DateTime(j,i+1,(Date)value,cf1));
}else{
wsheet.addCell(new Label(j,i+1,value+""));
}
}
}
book.write();
book.close();
}