最近在做一些需求,需要下載一些文件信息,最頻繁的就是下載excel文件到本地了
看過了很多方法,做個整理吧哈哈哈哈
參考的文章鏈接:
https://www.cnblogs.com/jiangweichao/p/9620940.html
https://www.jianshu.com/p/56680ce1cc97
https://www.cnblogs.com/jasmine-95/p/6054652.html
https://www.cnblogs.com/duke-peng/p/8862773.html
一、 將頁面中的html信息轉換為PDF文檔,下載到本地
先將html生成為圖片,再將圖片轉為pdf文檔
var target = document.getElementById('policy-information');// 是將target指向需要被生成的html內容
例如:(vue中)
<span v-html="emailContent" id="emailContentId"></span> //emailContent是定義好的html內容,並且在return里定義了 emailContent
此時的target為: var target = document.getElementById('emailContentId');
使用此方式時,vue需要安裝模塊:
npm install html2canvas jspdf --save
downPdf() { var that = this; var target = document.getElementById("policy-information");//policy-information是html的id信息 //target.style.background = "#FFFFFF"; html2canvas(target, { "imageTimeout": 0, 'scale': 2, }).then(canvas => { var contentWidth = canvas.width; var contentHeight = canvas.height; //一頁pdf顯示html頁面生成的canvas高度; var pageHeight = contentWidth / 592.28 * 841.89; //未生成pdf的html頁面高度 var leftHeight = contentHeight; //頁面偏移 var position = 0; //a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高 var imgWidth = 595.28; var imgHeight = 592.28 / contentWidth * contentHeight; var pageData = canvas.toDataURL('image/jpeg', 1.0); var pdf = new jspdf('', 'pt', 'a4'); //有兩個高度需區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89) //當內容未超過pdf一頁顯示的范圍,無需分頁 if(leftHeight < pageHeight) { pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else { while(leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight; position -= 841.89; //避免添加空白頁 if(leftHeight > 0) { pdf.addPage(); } } } var name = 'content-' + that.plcNo + '.pdf'; // 定義生成的pdf的文件名字 pdf.save(name); }); },
二、獲取后台返回的流數據,並下載pdf zip xlsx word ...
(這種方法我嘗試的時候發現它能下載excel,但是打不開,總是報錯... 由於當時在解決問題 就換了種方式去實現了 僅供參考)
/** 后台返回的字節流 下載 */ downloadPDF () { let that = this; $.ajax({ url:'http://localhost:8080/download' //后台下載信息的請求鏈接 type: "GET", responseType: 'arraybuffer', success: function(response){ //response為后台返回的流數據信息 //msword pdf zip // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這里表示xlsx類型 var blob = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); var downloadElement = document.createElement('a'); var href = window.URL.createObjectURL(blob); // 創建下載的鏈接 downloadElement.href = href; downloadElement.download = '表格'+'.xlsx'; // 下載后文件名 document.body.appendChild(downloadElement); downloadElement.click(); // 點擊下載 document.body.removeChild(downloadElement); // 下載完成移除元素 window.URL.revokeObjectURL(href); // 釋放掉blob對象 }, error: function(data) { alert("下載失敗"+data); } }); },
三、后台生成Excel,前端直接獲取並下載Excel
這大概是最簡單的方式吧,直接使用請求去訪問后台,然后使用window.open打開就可以了
3.1 get方式請求后台,直接使用window.open打開請求結果。
downLoadExcel(){
window.open('http://localhost:8080/ens-notify/excelDownload?batchcode='+this.batchCode); }
3.2 Form表單方式請求后台,直接下載excel文件
exportAllExcel() { var tt = new Date().getTime(); var url ="http://localhost:8080"+"/excelDownload"; /** * 使用form表單來發送請求 * 1.method屬性用來設置請求的類型——post還是get * 2.action屬性用來設置請求路徑。 * */ var form=$("<form>");//定義一個form表單 form.attr("style","display:none"); form.attr("target",""); form.attr("method","post"); //請求類型 如果是get請求可以改為get form.attr("action",url); //請求地址 $("body").append(form);//將表單放置在web中 /** * input標簽主要用來傳遞請求所需的參數: * * 1.name屬性是傳遞請求所需的參數名. * 2.value屬性是傳遞請求所需的參數值. * * 3.當為get類型時,請求所需的參數用input標簽來傳遞,直接寫在URL后面是無效的。 * 4.當為post類型時,queryString參數直接寫在URL后面,formData參數則用input標簽傳遞 * 有多少數據則使用多少input標簽 * */ var input1=$("<input>");input1.attr("type","hidden");input1.attr("name","batchcode"); input1.attr("value",'2018120601');form.append(input1); var input2=$("<input>");input2.attr("type","hidden");input2.attr("name","msgState"); input2.attr("value",'0');form.append(input2); var input3=$("<input>");input3.attr("type","hidden");input3.attr("name","businessType"); input3.attr("value",'P');form.append(input3); var input4=$("<input>");input4.attr("type","hidden");input4.attr("name","origin"); input4.attr("value",'222');form.append(input4); var input5=$("<input>");input5.attr("type","hidden");input5.attr("name","createDate"); input5.attr("value",tt);form.append(input5); form.submit();//表單提交 },
3.3 Ajax異步交互
$.ajax({ url: "http://localhost:8080"+"/excelDownload", type: "GET", //請求方式可變為post contentType: "application/json", data: { batchcode:this.batchCode, msgState:this.msgState, businessType:this.businessType, origin:this.origin, createDate:this.createDate }, success: function(response) { var blob = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); var downloadElement = document.createElement('a'); var href = window.URL.createObjectURL(blob); // 創建下載的鏈接 downloadElement.href = href; downloadElement.download = '111.xlsx'; // 下載后文件名 document.body.appendChild(downloadElement); downloadElement.click(); // 點擊下載 window.URL.revokeObjectURL(href); // 釋放掉blob對象 } });
四、.根據頁面的table數據導出Excel
使用這種方式導出Excel,需要再vue中安裝三個插件,並且導入兩個js文件放在src下
npm install -S file-saver xlsx
npm install -D script-loader
並且從網上下載js文件: Blob.js和Export2Excal.js
放在項目的src/excel_plugin 目錄下
exportChooseExcel: function() { // 兼容ie10哦! require.ensure([], () => { const { export_json_to_excel } = require('../excel_plugin/Export2Excel'); // 引入文件 //消息號 PDF 生成批次號 保單號 客戶號 消息類型 業務分類 接收人類型 模板 ID 消息創建者 創建時間 狀態 const tHeader = ['消息號', 'PDF 生成批次號', '保單號', '客戶號', '業務分類' ,'模板 ID', '狀態' ,'創建時間', 'printFileId']; //Excel的列名稱信息定義
const filterVal = ['msgId', 'batchCode', 'biztypeno', 'custno', 'businessType' ,'templateId', 'msgstate' ,'createdDate', 'printFileId']; // const list = this.multipleSelection; //這是表格中的數據內容 (需要導出的數據內容信息 tableData) const data = this.formatJson(filterVal, list); export_json_to_excel(tHeader, data, '列表excel'); //列頭信息 數據內容 導出的excel文件名字 }) }, formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => v[j])) }