Response方式导出Excel

原创
2017/02/09 16:21
阅读数 9.6K

一段破代码老忘。。。

  	protected void downloadPaginExcel(HttpServletRequest request, HttpServletResponse response,Pagin<?> pagin,String fileName) throws Exception{
    	String columnObject = getParameter("columnObject");//字段对应关系
    	JSONArray myJsonArray =JSONArray.parseArray(columnObject);
    	HSSFWorkbook wb = new HSSFWorkbook(); 
    	HSSFSheet sheet = wb.createSheet("工作表1");  
    	sheet.setDefaultColumnWidth(18);  
    	sheet.setDefaultRowHeightInPoints(20);  
    	HSSFRow row = sheet.createRow((int) 0);
        for(int i=0;i<myJsonArray.size();i++){
    		JSONObject newColumn = (JSONObject) myJsonArray.get(i);
    		String colName = (String) newColumn.get("title");
    		HSSFCell cell = row.createCell(i);
        	cell.setCellValue(colName);
    	}
        
        for(int i=0;i< pagin.getResultList().size();i++){
        	Map<String,Object> newMap=ConvertObjToMap(pagin.getResultList().get(i));
        	row = sheet.createRow((int) i + 1); 
        	for(int j=0;j<myJsonArray.size();j++){
        		JSONObject newColumn = (JSONObject) myJsonArray.get(j);
        		String col = (String) newColumn.get("dataIndex");
        		String valueNew =String.valueOf(newMap.get(col)) ;
        		row.createCell(j).setCellValue(valueNew);
        	}
        }
        String newFileName=fileName+".xls";
    	response.setContentType("application/vnd.ms-excel");   
        response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(newFileName, "UTF-8"));   
        OutputStream ouputStream = response.getOutputStream();   
        wb.write(ouputStream);
        ouputStream.flush();   
        ouputStream.close(); 
    }

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部