vue解析本地excel文件数据加入新的数组到最后一行不是最后一列有头
<p>部和数据部分:</p>
<p>可以使用第三方库xlsx,具体步骤如下:</p>
<ol>
<li>
<p>安装xlsx库:npm install xlsx --save</p>
</li>
<li>
<p>在需要解析excel文件的组件中引入xlsx库:</p>
</li>
</ol>
<p>import XLSX from 'xlsx';</p>
<ol start="3">
<li>通过FileReader对象读取本地excel文件:</li>
</ol>
<p>const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
const newData = ['new column1', 'new column2', 'new column3'];
jsonData.push(newData);
}</p>
<ol start="4">
<li>
<p>通过XLSX.utils.sheet_to_json()方法将excel表格转为json数据,其中header: 1表示解析表格时使用第一行作为表头;</p>
</li>
<li>
<p>创建一个新的数组newData,将需要加入到最后一行的数据添加到该数组中;</p>
</li>
<li>
<p>将newData添加到jsonData数组的末尾,即可将新数据加入到最后一行。</p>
</li>
</ol>
<p>完整代码示例:</p>
<template>
<div>
<input type="file" @change="handleFileChange">
<table>
<thead>
<tr>
<th v-for="header in headers">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in data" :key="index">
<td v-for="cell in row">{{ cell }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import XLSX from 'xlsx';
export default {
data() {
return {
headers: [],
data: [],
};
},
methods: {
handleFileChange(e) {
const file = e.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
const newData = ['new column1', 'new column2', 'new column3'];
jsonData.push(newData);
const headers = jsonData[0];
const data = jsonData.slice(1);
this.headers = headers;
this.data = data;
};
reader.readAsBinaryString(file);
},
},
};
</script
原文地址: https://www.cveoy.top/t/topic/hfHM 著作权归作者所有。请勿转载和采集!