使用Element UI 的Upload组件读取csv文件并转化为array对象
- 组件代码,此处使用 :http-request 覆盖原有代码提交方式,通过:on-change="readCsv" 在选择文件后操作文件,具体参数参考官方文档
<el-upload
ref="uploadFile"
:auto-upload="false"
:http-request="requestFile"
:limit="1"
:multiple="false"
:on-change="readCsv"
:show-file-list="false"
accept=".csv"
action="Fake Action"
class="upload-demo"
style="margin-right: 10px"
>
<el-button
type="primary">选择文件
</el-button>
</el-upload>
-
readCsv方法
//读取数据 readCsv(file, fileList) { let reader = new FileReader(); reader.readAsText(file.raw, "UTF-8"); reader.onload = function (evt) { // 读取文件内容 csv格式 let fileString = evt.target.result; //转化为array对象 let data = this.csvToArray(fileString); } //最后清楚选择文件信息,可以再进行选择文件继续操作 this.$refs.uploadFile.clearFiles(); }, //将csv数据转化为 data数据,delimiter可选分割方式 csvToArray(str, delimiter = ",") { const headers = str.slice(0, str.indexOf("\n")).split(delimiter); const rows = str.slice(str.indexOf("\n") + 1).split("\n"); return rows.map((row) => { const values = row.split(delimiter); return headers.reduce((object, header, index) => { object[header] = values[index]; return object; }, {}); }); },
本文来自博客园,作者:怀瑾于轻,转载请注明原文链接:https://www.cnblogs.com/hjyq/p/16544546.html

浙公网安备 33010602011771号