安装依赖 npm install xlsx npm i mammoth --save 引入 import XLSX from 'xlsx' import * as mammoth from 'mammoth'
<div style="display: flex; justify-content: center;"> <div> <el-button id="file-button" type="primary" @click="handlePreview" style="width: 104px;margin-bottom: 10px">上传文件</el-button> <input type="file" name="file" style="display: none"> <br> <el-button @click="showText()">显示文件内容</el-button> </div> <div> <textarea id="file-textarea" style="width: 500px;height: 500px" /> </div> </div>
handlePreview() { const input = document.querySelector('input[type=file]') input.click() }, showText() { const input = document.querySelector('input[type=file]') if (!input) { this.$notify.error('请先上传文件') } const file = input.files[0] const type = file.name.substring(file.name.lastIndexOf('.') + 1) const reader = new FileReader() if (type === 'txt') { reader.readAsText(file) reader.onload = function() { if (reader.result) { document.querySelector('#file-textarea').innerHTML = reader.result } } } if (type === 'xlsx') { reader.readAsBinaryString(file) reader.onload = (ev) => { try { const data = ev.target.result const workbook = XLSX.read(data, { type: 'binary' }) const wsname = workbook.SheetNames[0] const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容 let str = '' ws.forEach((item) => { str += Object.values(item) + '\n' }) document.querySelector('#file-textarea').innerHTML = str } catch (e) { return false } } } if (type === 'docx') { reader.readAsArrayBuffer(file) reader.onload = e => { const data = reader.result mammoth.extractRawText({ arrayBuffer: data }).then(r => { document.querySelector('#file-textarea').innerHTML = r.value }) } } },
标签:文件,vue,const,xlsx,file,reader,input,type From: https://www.cnblogs.com/angia/p/16592460.html