js-xlsx vue import excel online preview
Import XLSX library
Official address Github
installation
npm install xlsx --s
Introduce
import XLSX from ‘xlsx’
HTML
<template>
<div class="upload-container">
<el-upload
ref="upload"
action="/"
:show-file-list="false"
:on-change="importExcel"
:auto-upload="false"
style="margin-bottom: 20px"
>
<el-button
slot="trigger"
icon="el-icon-upload"
size="small"
type="primary"
>
上传文件
</el-button>
</el-upload>
<el-tabs
v-if="xlsxJson && xlsxJson.length"
v-model="activeName"
type="card"
@tab-click="handleClick"
>
<el-tab-pane
v-for="(item, index) in xlsxJson"
:key="index"
:label="item.sheetName"
:name="'tab' + '-' + index"
>
<el-table ref="tableSort" :height="height" :data="item.sheet">
<el-table-column
show-overflow-tooltip
width="95"
v-for="(value, key, index) in item.sheet[0]"
:key="index"
:label="key"
:prop="key"
></el-table-column>
</el-table>
</el-tab-pane>
</el-tabs>
</div>
</template>
JS
<script>
import XLSX from 'xlsx'
export default {
name: 'Upload',
data() {
return {
xlsxJson: [],
activeName: '',
}
},
methods: {
handleClick(tab, event) {
console.log(tab, event)
},
importExcel(file) {
// let file = file.files[0] // 使用传统的input方法需要加上这一步
const types = file.name.split('.')[1]
const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(
(item) => item === types
)
if (!fileType) {
this.$message('格式错误!请重新选择')
return
}
this.file2Xce(file).then((tabJson) => {
if (tabJson && tabJson.length > 0) {
this.xlsxJson = tabJson
console.log('数据', this.xlsxJson)
this.activeName = 'tab-0'
// xlsxJson就是解析出来的json数据,数据格式如下
// [
// {
// sheetName: sheet1
// sheet: sheetData
// }
// ]
}
})
},
file2Xce(file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
reader.onload = function (e) {
const data = e.target.result
this.wb = XLSX.read(data, {
type: 'binary',
})
const result = []
this.wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName: sheetName,
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
})
})
resolve(result)
}
reader.readAsBinaryString(file.raw)
// reader.readAsBinaryString(file) // 传统input方法
})
},
},
computed: {
height() {
return this.$baseTableHeight()
},
},
}
</script>