天天看點

Excel上傳至伺服器與從伺服器彈框下載下傳到本地

報表的開發常常涉及到Excel的生成已經下載下傳至本地,本公司經常采用的是poi。下載下傳的時候把查詢的參數傳過去,擷取查詢資料,然後在下載下傳。而我這裡要寫的就是Excel導入資料至資料庫,以及Excel的模本從伺服器下載下傳。

1.Excel導入資料至資料庫,首先要實作的就是把Excel上傳至伺服器,這裡要注意一下Excel的版本問題,Excel2007以前是.xls的字尾,而以後就是.xlsx。

    1.1前端的ajax請求:

$.ajax({  
						          url: 'tMonitorDrugList/addMonitorDrugList' ,  
						          type: 'POST',  
						          data: formData,  
						          async: false,  
						          cache: false,  
						          contentType: false,  
						          processData: false,  
						          success: function (returndata) {  
						              alert(returndata);  
						          },  
						          error: function (returndata) {  
						              alert(returndata);  
						          }  
						     });  
           

1.2controller中方法:

@RequestMapping(value ="/addMonitorDrugList")
	@ResponseBody
	public Map<String,Object> addMonitorDrugList(ModelMap modelMap, MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException{
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String filePath = fileUpload(file, request); 
		System.out.println(filePath);
	    return resultMap;
	}

/**
	 *  檔案上傳至伺服器
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private String fileUpload(MultipartFile file, HttpServletRequest request)
			throws IOException {
		/*
		//判斷是不是Multipart送出
		if(ServletFileUpload.isMultipartContent(request)){
			System.out.println("是Multipart");
		}else{
			System.out.println("不是Multipart");
		}*/
		String path = request.getSession().getServletContext().getRealPath("upload");  
		path =path + File.separatorChar + DateUtils.getYearAndMonthString() ;
		String fileName = file.getOriginalFilename();  
		String[] fileNames =fileName.split("\\.");
		fileName = fileNames[0]+"_"+DateUtils.getTimeString()+"."+fileNames[1];
        File dir = new File(path,fileName);
        String filePath =path+File.separator+fileName;
        if(!dir.exists()){  
            dir.mkdirs();  
        }  
	    file.transferTo(dir);
	    return filePath;
	}
           

2.Excel模本的下載下傳,我們把excel模本放在服務以供客戶下載下傳,Excel的 下載下傳,我們隻要設定response的一些特定的參數即可,但是這裡我們要注意的是,檔案下載下傳不要采用ajax異步請求的方式。原因:因為response原因,一般請求浏覽器是會處理伺服器輸出的response,例如生成png、檔案下載下傳等,然而ajax請求隻是個“字元型”的請求,即請求的内容是以文本類型存放的。檔案的下載下傳是以二進制形式進行的,雖然可以讀取到傳回的response,但隻是讀取而已,是無法執行的,說白點就是js無法調用到浏覽器的下載下傳處理機制和程式。

Excel上傳至伺服器與從伺服器彈框下載下傳到本地

2.1前端js代碼:

//下載下傳模版
	$("#down_template").click(function(){
		$("#search_roleForm").submit();
	});
           

2.2controller中的方法。

/**
	 * 檔案從伺服器下載下傳
	 * @param filePath 檔案路徑
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void fileDown(String filePath, HttpServletRequest request, HttpServletResponse response){
		String fileName="監控資料模闆表格";
		File file = new File(filePath);
		if(!file.exists()){
			System.out.println("要下載下傳的檔案不存在");
			return;
		}
		//設定response參數,可以打開下載下傳頁面
		response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");  
	    try {
			response.setHeader("Content-Disposition", "attachment;filename="
			     + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
	    BufferedInputStream bis = null;
	    BufferedOutputStream bos = null;
		try {
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while(-1!=(bytesRead=bis.read(buff,0,buff.length))){
				bos.write(buff,0,bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(bis!=null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bos!=null){
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}