自定义选行导出Excel表






downloadFile() { let selectIDs = [] selectIDs = JSON.parse(JSON.stringify(this.newListArr)) /*post(exportCustomMItemDataWithLine, { selectIDs }).then(res => { let data = res if (!data) { return } const url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') let myDate = new Date() link.style.display = 'none' link.href = url link.setAttribute('download', '数据查询导出' + date2md(myDate) + '.xls') document.body.appendChild(link) link.click() document.body.removeChild(link) //下载完成移除元素 window.URL.revokeObjectURL(url) //释放掉blob对象 })*/ this.params.selectIDs = selectIDs axios({ method: 'post', url: exportCustomMItemDataWithLine, data: this.params, responseType: 'blob' }).then(res => { if (!res) { return } const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) const fileName = res.headers['content-disposition'].split('=')[1] let url = '' let isBlob = false const errMsg = '下载出错,文件数据无法识别!' let data = blob if (data instanceof Blob) { isBlob = true url = window.URL.createObjectURL(data) } else if (typeof data == 'string') { // base64编码 url = data } else { Message.error(errMsg) return } if ('download' in document.createElement('a')) { // 非IE下载 const tmpLink = document.createElement('a') tmpLink.download = fileName || '' tmpLink.style.display = 'none' tmpLink.href = url document.body.appendChild(tmpLink) tmpLink.click() window.URL.revokeObjectURL(tmpLink.href) document.body.removeChild(tmpLink) } else { // IE10+下载 if (isBlob) { window.navigator.msSaveBlob(data, fileName) } else { console.log(errMsg) return } } }) this.selectCheckbox = [] this.tableHeadInfo.forEach(item => { item.checked = false }) this.$refs.multipleTable.clearSelection() this.selectIDs = [] },
axios方法精髓部分:
axios({ method: 'post', url: exportCustomMItemDataWithLine, data: this.params, responseType: 'blob' }).then(res => { if (!res) { return } const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) const fileName = res.headers['content-disposition'].split('=')[1] let url = '' let isBlob = false const errMsg = '下载出错,文件数据无法识别!' let data = blob if (data instanceof Blob) { isBlob = true url = window.URL.createObjectURL(data) } else if (typeof data == 'string') { // base64编码 url = data } else { Message.error(errMsg) return } if ('download' in document.createElement('a')) { // 非IE下载 const tmpLink = document.createElement('a') tmpLink.download = fileName || '' tmpLink.style.display = 'none' tmpLink.href = url document.body.appendChild(tmpLink) tmpLink.click() window.URL.revokeObjectURL(tmpLink.href) document.body.removeChild(tmpLink) } else { // IE10+下载 if (isBlob) { window.navigator.msSaveBlob(data, fileName) } else { console.log(errMsg) return } } })