当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

导出excel并提供下载

发表于: 2012-02-24   作者:酷的飞上天空   来源:转载   浏览:
摘要: 工作中需要动态生成excel并提供下载,留在这个为了以后方面COPY。       protected void responseExcel(String filename,List<String> title,List<String> mapKey,List<Map<String, Object>> repo

工作中需要动态生成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();
	}

 

导出excel并提供下载

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号