1. 安裝組件
cnpm install xlsx --save
2. 代碼
<template>
<span>
<input class="input-file" type="file" @change="exportData"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
<button @click="btnClick">導入EXCEL</button>
</span>
</template>
<script>
import XLSX from 'xlsx'
export default {
name: 'HelloWorld',
props: {
type: String,
default: '選擇excel文件'
},
methods: {
btnClick () {
document.querySelector('.input-file').click()
},
exportData (event) {
if (!event.currentTarget.files.length) {
return
}
const that = this
// 拿取文件對象
var f = event.currentTarget.files[0]
// 用FileReader來讀取
var reader = new FileReader()
// 重寫FileReader上的readAsBinaryString方法
FileReader.prototype.readAsBinaryString = function (f) {
var binary = ''
var wb // 讀取完成的數據
var outdata // 你需要的數據
var reader = new FileReader()
reader.onload = function (e) {
// 讀取成Uint8Array,再轉換為Unicode編碼(Unicode占兩個字節)
var bytes = new Uint8Array(reader.result)
var length = bytes.byteLength
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
// 接下來就是xlsx了,具體可看api
wb = XLSX.read(binary, {
type: 'binary'
})
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
// 自定義方法向父組件傳遞數據
console.log('outdata = ' + JSON.stringify(outdata))
that.$emit('getResult', outdata)
}
reader.readAsArrayBuffer(f)
}
reader.readAsBinaryString(f)
}
}
}
</script>
<style scoped>
.input-file {
display: none;
}
</style>
讀取EXCEL中的日期類型時,需要時間轉換 // excel讀取2018/01/01這種時間格式是會將它裝換成數字類似於46254.1545151415 numb是傳過來的整數數字 formatDate (numb) { const time = new Date((numb - 1) * 24 * 3600000 + 1) time.setYear(time.getFullYear() - 70) return time },
