txt及excel文件流转文字
作者:互联网
"xlsx": "^0.16.0"
import XLSX from 'xlsx'
<input
type="file"
ref="inputFile"
accept=".xls,.xlsx,.txt"
@change="readFile($event)"
/>
async readFile(e) { const files = e.target.files if (files.length <= 0) { return } else if (!/(xls|xlsx|txt)$/.test(files[0].name.toLowerCase())) { this.$message.warning('上传格式不正确,请上传xls、xlsx或者txt格式') } else { this.uploadFile = files[0].name } let dataBinary = null if (/(xls|xlsx)$/.test(files[0].name.toLowerCase())) { dataBinary = await this.readExcel(files[0]) } else if (/(txt)$/.test(files[0].name.toLowerCase())) { dataBinary = await this.readTxt(files[0]) } console.log(dataBinary) }, // 读取excel文件并返回数据 readExcel(file) { return new Promise(resolve => { const fileReader = new FileReader() fileReader.readAsBinaryString(file) fileReader.onload = ev => { try { const data = ev.target.result const workbook = XLSX.read(data, { type: 'binary' }) const wsname = workbook.SheetNames[0] //取第一张表 //添加{header:1},表示第一行不为标题,直接作为内容解析 const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], {header: 1}) //生产json表格内容 resolve(ws) } catch (e) { return false } } }) }, // 读取txt文件并返回数据 readTxt(file) { return new Promise(resolve => { const fileReader = new FileReader() fileReader.readAsText(file) fileReader.onload = ev => { try { let data = ev.target.result console.log(data) // 根据逗号(中英都可),或者回车分割字符串 data = data.split(/[,,\s\n]/).filter(_ => _) resolve(data) } catch (e) { return false } } }) },
标签:XLSX,ev,const,fileReader,excel,流转,file,txt,data 来源: https://www.cnblogs.com/wxyblog/p/16265982.html