// data
const data = [
{
id: 1,
合并的列頭1: '數(shù)據(jù)11',
合并的列頭2: '數(shù)據(jù)12',
_style: { font: { sz: 14, bold: true, color: { rgb: 'FFFFAA00' } } },
_merges: [{ s: { c: 1, r: 0 }, e: { c: 4, r: 0 } }],
},
]
const utils = {
writeFile(data, { tableName = 'sheet1', fileName = '下載', type = 'xlsx', title, head } = {}) {
const bookType = { xlsx: 'xlsx', xls: 'biff8' }
// 處理數(shù)據(jù)
const tmpdata = this.dataHandle(data, title, head)
// 設(shè)置區(qū)域 比如表格從A1到D10
const outputPos = Object.keys(tmpdata)
// tmpdata['B1'].s = // 單元格樣式
// tmpdata['!merges'] = [{ s: { c: 1, r: 0 }, e: { c: 4, r: 0 } }] // 合并單元格
const wb = {
SheetNames: [tableName], //保存的表標(biāo)題
Sheets: {
[tableName]: {
...tmpdata, // 數(shù)據(jù)
'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1], // 設(shè)置填充區(qū)域
},
},
}
const xlsxDataStr = XLSX.write(wb, { ...this.wopts, bookType: bookType[type] })
const bolb = new Blob([this.str2Buffer(xlsxDataStr)])
this.saveAs(bolb, `${fileName}.${type}`)
},
// 瀏覽器下載
saveAs(data, fileName) {
const tmpa = document.createElement('a')
tmpa.download = fileName
tmpa.href = URL.createObjectURL(data)
tmpa.click()
setTimeout(function() {
URL.revokeObjectURL(data)
}, 100)
},
// 處理數(shù)據(jù) ==> { A1: {v:1}, A2: {v:2} }
dataHandle(head = [], title = [], data = []) {
const tmpdata = {}
;[...head, ...title, ...data].forEach((item, index) => {
const row = index + 1
const { _style, _merges, ...other } = item
Object.values(other).forEach((i, ind) => {
const col = this.transNum2Char(ind)
const val = { v: i }
if (_style) val.s = _style
tmpdata[col + row] = val
})
})
return tmpdata
},
// 保存格式
wopts: { bookType: 'xlsx', bookSST: false, type: 'binary', cellStyles: true },
// 0 > A, 26 > AA
transNum2Char(num) {
// 保存每一位的 unicode 碼
let arr = []
// 679 % 26 % 26 % 26 ===> [3, 1, 0]
while (num >= 26) {
arr.push((num % 26) + 1) // 0-25 需轉(zhuǎn)換成 1-26
num = parseInt(num / 26)
}
arr.push(num + 1) // 0-25 需轉(zhuǎn)換成 1-26
return arr
.reverse()
.map((i) => String.fromCharCode(i + 64))
.join('')
},
// 將字符串轉(zhuǎn)換成 buffer
str2Buffer(s) {
const buf = new ArrayBuffer(s.length)
const view = new Uint8Array(buf)
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
return buf
},
}