1.前端dom导出,展示啥导出啥
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
setTimeout(() => {
var lastName = 'xlsx' // txt
var wb = XLSX.utils.book_new()
var table = document.getElementById('exportTankTable') //el-table的id:exportTankTable
//若导出无表头表格
// var table = document.querySelector('#exportTankTable .el-table__body-wrapper')
var ws1 = XLSX.utils.table_to_sheet(table)
XLSX.utils.book_append_sheet(wb, ws1, this.console_title)
/* get binary string as output */
var wbout = XLSX.write(wb, { bookType: lastName, bookSST: true, type: 'array' })
try {
FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '文件名.' + lastName)
} catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
return wbout
}, 1)
// 2.后端返回文件流 + token(post/get请求)
import qs from 'qs'
var params = {
jsonObject: JSON.stringify(this.listQuery), // 数据得查询条件(Json 字符串) JSON.stringify(this.listQuery)
fileName: '文件名.xlsx',// 文件得名称
excelTitles:'姓名,性别',// 表头
excelFileds:'name,sex',// 表头对应字段
language:'zh'
}
axios({
method: 'post', //或者get
url: window.glob.baseUrl + url, // url为接口
headers: { Authorization: JSON.parse(sessionStorage.getItem('token')) }, // token
data: qs.stringify(params), // 传值
responseType: 'blob'
}).then(res => {
// 文件下载
const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 下载.txt时type为text/plain
let link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.setAttribute('download', '文件名.xlsx')
link.click()
link = null
})
// 3.后端返回文件流(get请求)
window.open(window.glob.baseUrl + 'table/export?id=' + id + '&tankNo=' + tankNo)
// 4.后端返回文件流。提交表单,请求头无法修改,无法加token
var PARAMS = {
jsonObject: JSON.stringify(this.listQuery), // 数据得查询条件(Json 字符串) JSON.stringify(this.listQuery)
fileName: '文件名.xlsx',// 文件得名称
excelTitles:'姓名,性别',// 表头
excelFileds:'name,sex',// 表头对应字段
language:'zh'
}
var temp = document.createElement('form')
temp.action = window.glob.baseUrl + url
temp.method = 'post'
temp.style.display = 'none'
for (var x in PARAMS) {
var opt = document.createElement('textarea')
opt.name = x
opt.value = PARAMS[x]
temp.appendChild(opt)
}
document.body.appendChild(temp)
temp.submit()
return temp
// 5.导出数据为后台接口返回所有数据,分页查询接口不适用
import { export_json_to_excel } from '@/utils/export/Export2Excel'
export2Excel(resData) { // resData为后台返回数据
require.ensure([], () => {
// updateHeader为表格数据,如:
this.updateHeader = [
{
label:'姓名',
prop:'name'
},
{
label:'性别',
prop:'sex'
}
]
const tHeader = this.updateHeader.map(item => { return item.label })
const filterVal = this.updateHeader.map(item => { return item.prop })
const data = this.formatJson(filterVal, resData)
export_json_to_excel(tHeader, data, '销售记录')
})
},
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
}