Vue 中解析 Public 目录下 Excel 文件并修改内容
在 Vue 中直接获取 public 下边的文件是不可行的,因为 public 目录下的文件只是静态资源,只能通过 http 协议进行访问。因此,需要通过 http 请求来获取并解析 excel 文件。
以下是一个示例代码,展示如何通过 axios 库发送 http 请求获取 excel 文件并解析:
<template>
<div>
<button @click="handleClick">点击获取 excel 文件</button>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in dataList" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.gender }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios';
import XLSX from 'xlsx';
export default {
data() {
return {
dataList: []
}
},
methods: {
handleClick() {
axios.get('/data.xlsx', { responseType: 'arraybuffer' })
.then(res => {
const data = new Uint8Array(res.data);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(worksheet);
this.dataList = json;
})
.catch(err => {
console.log(err);
})
}
}
}
</script>
在该示例代码中,我们通过 axios 库发送 http GET 请求获取 excel 文件,同时设置 responseType 为 arraybuffer,以获取文件内容的二进制数据。获取到数据后,我们使用 XLSX 库来解析 excel 文件,并将数据转换为 JSON 格式,最后将数据展示在表格中。
需要注意的是,这里我们假设 excel 文件中只有一个 sheet,因此我们直接获取第一个 sheet 进行解析。如果 excel 文件中有多个 sheet 需要解析,则需要根据实际情况进行处理。同时,需要在项目中安装 axios 和 xlsx 库,以便引入使用。
原文地址: https://www.cveoy.top/t/topic/oFeb 著作权归作者所有。请勿转载和采集!