安裝xlsx
cnpm install xlsx
JS:
import XLSX from 'xlsx'
const EXCEL = class {
construct () {}
/**
* [exportsEXCL 導(dǎo)出數(shù)據(jù)到excel]
* @param {Array} [_headers=[]] [表頭]
* @param {Array} [_body=[]] [內(nèi)容]
* @param {String} [name='excel'}] [文件名]
* @return {[type]} [無]
*/
exportsEXCL ({_headers = [], _body = [], name = 'excel'}) {
// 獲取header和body
const header = _headers
.map((v, i) => Object.assign({}, {v, position: String.fromCharCode(65 + i) + 1}))
.reduce((prev, value) => Object.assign({}, prev, {[value.position]: {v: value.v}}), {})
const body = _body
.map((v, i) => _headers.map((k, j) => Object.assign({}, { v: v[k], position: String.fromCharCode(65 + j) + (i + 2) }))) //!!!
.reduce((prev, value) => prev.concat(value))
.reduce((prev, value) => Object.assign({}, prev, {[value.position]: {v: value.v}}), {})
// 合并headers和data
const output = Object.assign({}, header, body)
// 獲取所有單元格位置
const outputPos = Object.keys(output)
// 計(jì)算出范圍
const ref = outputPos[0] + ':' + outputPos[outputPos.length - 1]
// 構(gòu)建 workbook 對(duì)象
const wb = {
SheetNames: ['mySheet'],
Sheets: {
'mySheet': Object.assign({}, output, { '!ref': ref })
}
}
// 導(dǎo)出 Excel
XLSX.writeFile(wb, `${name}.xlsx`)
}
/**
* [exportsCSV 導(dǎo)出數(shù)據(jù)到CSV] ---解決大數(shù)據(jù)下載
* @param {Array} [_headers=[]] [表頭]
* @param {Array} [_body=[]] [內(nèi)容]
* @param {String} [name='excel'}] [文件名]
* @return {[type]} [無]
*/
exportsCSV ({_headers = [], _body = [], name = 'csv', callback = function () {}}) {
const headers = _headers.join() + '\n' // 格式化表頭
const body = _body.map(item => { // 格式化表內(nèi)容
return Object.values(item).join() + '\n'
})
const output = headers.concat(body) // 合并
const BOM = '\uFEFF'
// 創(chuàng)建一個(gè)文件CSV文件
var blob = new Blob([BOM + output], {type: 'text/csv'})
// IE
if (navigator.msSaveOrOpenBlob) {
// 解決大文件下載失敗
// 保存到本地文件
navigator.msSaveOrOpenBlob(blob, `${name}.csv`)
} else {
let downloadLink = document.createElement('a')
// 因?yàn)閡rl有最大長(zhǎng)度限制,encodeURI是會(huì)把字符串轉(zhuǎn)化為url靡努,超出限制長(zhǎng)度部分?jǐn)?shù)據(jù)丟失導(dǎo)致下載失敗,
// 為此采用創(chuàng)建Blob(二進(jìn)制大對(duì)象)的方式來存放緩存數(shù)據(jù)炊琉,具體代碼如下:
downloadLink.setAttribute('href', URL.createObjectURL(blob))
downloadLink.download = `${name}.csv`
document.body.appendChild(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink)
}
callback()
}
}
exports.defalut = new EXCEL()
注: 使用 Blob 和 msSaveBlob 以本地方式保存文件(任意大小):https://blog.csdn.net/p312011150/article/details/78930976