vue读取public下边的excel文件
Vue无法直接读取public下的excel文件,需要使用第三方库来读取。常用的库有js-xlsx和xlsx。下面是一个使用js-xlsx读取excel文件的示例代码:
- 安装js-xlsx
npm install xlsx
- 在Vue组件中引入js-xlsx
import XLSX from 'xlsx'
- 在需要读取excel文件的方法中,使用FileReader读取文件,并将文件内容转换为二进制字符串,然后使用js-xlsx的方法解析文件内容。示例代码如下:
// 读取excel文件
readExcelFile(event) {
// 获取文件对象
const file = event.target.files[0]
// 创建FileReader对象
const reader = new FileReader()
// 读取文件内容
reader.readAsBinaryString(file)
// 文件读取完成后的回调函数
reader.onload = () => {
// 将文件内容转为二进制字符串
const data = reader.result
// 使用js-xlsx的方法解析文件内容
const workbook = XLSX.read(data, { type: 'binary' })
// 获取第一个工作表的数据
const sheetData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
console.log(sheetData)
}
}
- 在模板中添加文件选择器,触发文件读取方法
<template>
<div>
<input type="file" @change="readExcelFile">
</div>
</template>
``
原文地址: http://www.cveoy.top/t/topic/hchp 著作权归作者所有。请勿转载和采集!