1. 程式人生 > >Java操作Excel之Excel檔案的下載

Java操作Excel之Excel檔案的下載

1、有的時候在Web應用會有下載Excel的需求,現分享下後臺實現下載Excel檔案的程式碼

 @RequestMapping(value = "/exportExcel",  method = {RequestMethod.GET})
	 public void exportExcel(CorplutionComparisonGroupCustomerDO corplutionComparisonGroupCustomerDO, HttpServletRequest request, HttpServletResponse response){
	     // 下載的Excel的檔名稱
	     String fileName = "客戶名單";
	     response.setContentType("application/vnd.ms-excel");  
	     String codedFileName = null;  
	     OutputStream ops = null;  
	     List<CorplutionComparisonGroupCustomerDO> corplutionContactList = new ArrayList<CorplutionComparisonGroupCustomerDO>();
	     try{  
	         // 進行轉碼,使其支援中文檔名  
			 codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");  
	         response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");  
	         // 產生工作簿物件  
	         //產生工作表物件  
    		 corplutionContactList = corplutionComparisonGroupCustomerFacade.findList(corplutionComparisonGroupCustomerDO);
	         Map<String, String> headMap = new LinkedHashMap<String, String>();
	         headMap.put("CID", "customerId");
	         headMap.put("客戶公司全稱", "companyFullName");
		   Map<String, Object> excelData = ExcelUtils.fillExcelData(headMap, corplutionContactList);
		   List<String> heads = (List<String>) excelData.get("heads");
		   List<List<String>> dataList = (List<List<String>>)excelData.get("dataList");
		   HSSFWorkbook workbook = ExcelUtils.createExcelFile(fileName, heads , dataList);  
	         ops = response.getOutputStream();  
	         workbook.write(ops);  
	     }catch(Exception e){
	    	 if (logger.isInfoEnabled()){
	    		 logger.error("匯出excel異常", e);
	    	 }
	     }
	}

2、有關ExcelUtils.java的實現,可以參考上一篇部落格的部落格