参考文档
最终效果
代码
<template>
<div class="test">
<input type="file" ref="fileRef" />
<button @click="read">读取excel数据</button>
</div>
</template>
<script>
import Excel from 'exceljs'
export default {
methods: {
read() {
const workbook = new Excel.Workbook()
// 这种方式不行 这种在浏览器上不适用
// https://github.com/Dream4ever/Knowledge-Base/issues/142
// workbook.xlsx.readFile('a.xlsx').then(() => {
// console.log(1)
// })
const file = this.$refs.fileRef.files[0]
// 1.将File类型转换成buffer
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend = (e) => {
const buffer = e.target.result
// 2.解析buffer
workbook.xlsx.load(buffer).then((res) => {
// console.log(res)
const worksheet = res.getWorksheet(1)
// sheet名称
const sheetName = worksheet.name
worksheet.eachRow((row, rowNumber) => {
// console.log(row, rowNumber)
row.eachCell((cell, colNumber) => {
let value = ''
// 判断单元格的类型
// 6-公式 ;2-数值;3-字符串。
if (cell.type == 6) {
value = cell.result
} else {
value = cell.value
}
console.log(
`当前为第${rowNumber}行,第${colNumber}列,值为:${value}`
)
})
})
})
}
// workbook.xlsx.load(file).then((res) => {
// // console.log(res)
// })
},
},
}
</script>
<style scoped></style>