導(dǎo)出excel
1、安裝依賴
npm install xlsx file-saver -S
npm install script-loader -S -D
2、需要兩個(gè)文件
Blob.js和 Export2Excel.js,可以百度下載
項(xiàng)目中新建一個(gè)文件夾vendor,放這兩個(gè)文件
3、vue寫方法
handleDownload() {
//請(qǐng)求后端接口拿到list數(shù)據(jù)
download().then(response => {
if (response.data) {
this.downList = response.data.data
} else {
this.downList = []
}
import('@/vendor/Export2Excel').then(excel => {
const tHeader = ['編號(hào)', '地市', '姓名', '交易金額', '下單時(shí)間']
//表格第一行標(biāo)題
const filterVal = ['orderId', 'cityName', 'Name', 'payAmount', 'creatDate']
//表格跟接口字段對(duì)應(yīng)
const list = this.downList
const data = this.formatJson(filterVal, list) //數(shù)據(jù)過(guò)濾
excel.export_json_to_excel({
header: tHeader, //表頭 必填
data, //具體數(shù)據(jù) 必填
filename: 'excel-list', //文件名 非必填
autoWidth: true, //單元格是否要自適應(yīng)寬度 非必填
bookType: 'xlsx' //非必填?
})
this.downloadLoading = false
})
}).catch(() => {
this.downloadLoading = false
})
},
// 過(guò)濾數(shù)據(jù)方法,例如時(shí)間格式
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
if (j === 'creatDate') {
var date = new Date(v[j])
return formatTime(date, 'yyyy-MM-dd hh:mm:ss')
} else {
return v[j]
}
}))
},
上傳文件 格式要注意
const formData = new FormData()
formData.append('token', getToken())
formData.append('file', data.file)
formData.append('appName', data.appName)
請(qǐng)求接口配置post
{
url: '.....',
method: 'POST',
data: formData,
headers: {
'Content-Type': 'multipart/form-data'
}
``
步驟和傳圖片一樣