EXCEL文件下載(js、java)


下載的js:

/**
 * @param target_URL 下載地址
 * @param onload 服務器返回結果的回調函數
 * @param fileName 文件名 不傳則從服務端獲取 Content-disposition filename=*
 * @param save_URL 保存路徑 先不寫了
 */
function downLoadFile(target_url,onloadFunction,filename,save_URL){
    var req = new XMLHttpRequest();
    req.open("POST", target_url, true);
    req.responseType = "blob";
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            if(!filename){
                filename = req.getResponseHeader("Content-disposition");
                filename = filename.substring(filename.indexOf("filename=")+9,filename.length);
                filename = decodeURI(filename);
            }
            
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(req.response);
                link.download = filename;
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([req.response], { type: 'application/force-download' });
                window.navigator.msSaveBlob(blob, filename);
            } else {
                // Firefox version
                var file = new File([req.response], filename, { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
        }
    };
     req.onload = onloadFunction;
    req.ontimeout = function(e) { 
        //下載超時
    };
    req.onerror = function(e) {
     //下載出錯
    };
    req.send();
}

 

java主要代碼:

File templetFile = new File(request.getSession().getServletContext().getRealPath("/")+"WEB-INF/teple/測試模板.xls");
downLoadExcel(response, new HSSFWorkbook(new FileInputStream(templetFile)),templetFile.getName());


private void downLoadExcel(HttpServletResponse response, Workbook workbook,String fileName){
        OutputStream output = null;
        try {
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename="+ URLEncoder.encode(fileName,"utf-8"));  
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            output = response.getOutputStream();
            workbook.write(output);
            output.flush();
        } catch (Exception e) {
            //異常處理
        } finally {
            try {if(output!=null)output.close();} catch (IOException e) {}
        }
    }

 

 

js調用:

  loading、loadingClose()為自定義遮罩

$("button[filter='downTemplet']").click(function(){
    loading();
    downLoadFile("resolveExcel",loadingClose());
 });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM