42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
|
|
import * as XLSX from 'xlsx'
|
||
|
|
|
||
|
|
export function downloadRename (blob, fileType, filename) {
|
||
|
|
const typesMap = {
|
||
|
|
xlsx: 'application/vnd.ms-excel',
|
||
|
|
xls: 'application/vnd.ms-excel',
|
||
|
|
pdf: 'application/pdf',
|
||
|
|
doc: 'application/msword',
|
||
|
|
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||
|
|
csv: 'text/csv'
|
||
|
|
}
|
||
|
|
const type = typesMap[fileType] || ''
|
||
|
|
const newBlob = new Blob([blob], { type })
|
||
|
|
const href = URL.createObjectURL(newBlob)
|
||
|
|
const a = document.createElement('a')
|
||
|
|
a.href = href
|
||
|
|
a.download = filename + '.' + fileType
|
||
|
|
document.body.appendChild(a)
|
||
|
|
a.click()
|
||
|
|
document.body.removeChild(a)
|
||
|
|
URL.revokeObjectURL(href)
|
||
|
|
}
|
||
|
|
|
||
|
|
export function readExcel (file) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
const reader = new FileReader()
|
||
|
|
reader.readAsBinaryString(file)
|
||
|
|
reader.onload = ev => {
|
||
|
|
try {
|
||
|
|
const data = ev.target.result
|
||
|
|
const workbook = XLSX.read(data, { type: 'binary' })
|
||
|
|
const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
|
||
|
|
const list = XLSX.utils.sheet_to_json(firstSheet)
|
||
|
|
resolve(list)
|
||
|
|
} catch (e) {
|
||
|
|
reject(e)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
reader.onerror = () => reject(new Error('文件读取失败'))
|
||
|
|
})
|
||
|
|
}
|