1. 安装: cnpm install xlsx --save // xlsx最新版本会报错,建议安装次新版
2. 新建uploadExcel.js文件
import Vue from 'vue'
import XLSX from 'xlsx'
/**
* 导入ex表格 得到json数据
* 已注入所有Vue实例,
* template模板里调用 $importf
* 组件方法里调用 this.$importf
* 例:<input type="file" id="file22" @change="importf('file22')" />
* this.$importf(id) 得到 json数据
*/
const importf = (id) => {
let promise = new Promise((resolve, reject) => {
// 导入
// FileReader共有4种读取方法:
// 1.readAsArrayBuffer(file) :将文件读取为ArrayBuffer。
// 2.readAsBinaryString(file) :将文件读取为二进制字符串
// 3.readAsDataURL(file) :将文件读取为Data URL
// 4.readAsText(file, [encoding]) :将文件读取为文本,encoding缺省值为'UTF-8'
var wb // 读取完成的数据
var rABS = false // 是否将文件读取为二进制字符串
let obj = document.getElementById(id)
if (!obj.files) {
return
}
var f = obj.files[0]
var reader = new FileReader()
if (rABS) {
reader.readAsArrayBuffer(f)
} else {
reader.readAsBinaryString(f)
}
var arr = []
reader.onload = function (e) {
var data = e.target.result
if (rABS) {
wb = XLSX.read(btoa(fixdata(data)), { // 手动转化
type: 'base64'
})
} else {
wb = XLSX.read(data, {
type: 'binary'
})
}
arr = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
resolve(arr)
}
reader.onerror = function (e) {
reject(arr)
}
})
return promise
}
const fixdata = (data) => { // 文件流转BinaryString
var o = ''
var l = 0
var w = 10240
for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
return o
}
Vue.prototype.$importf = importf
3. 在main.js文件里面引入uploadExcel.js文件
import '@/utils/uploadExcel'
4. 在组件中添加导入按钮:
HTML:
<input type="file" class="blue_input" name="file" id="file" :value="value" @click="clickAsync('file', $event.target.files, $event)"/>
<table style="margin: 20px 0;">
<thead>
<tr>
<th v-for="(head, index) in tableHeads">
{{index}}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, i) in tabelBody">
<td v-for="(head, index) in tableHeads">
{{item[index]}}
</td>
</tr>
</tbody>
</table>
data:
value: '',
tableHeads: [],//表头
contracts: [],//excel文件信息
tabelBody: [],//list数据
js:
clickAsync (idName, val, el) {
el.srcElement.value = ''
this.value = ''
this.contracts = []
this.tableHeads = []
this.tabelBody = []
document.getElementById(idName).addEventListener('change', async (e) => {
this.allItem = e.target.files
this.value = e.target.value
if (this.allItem.length > 0) {
this.$emit('clickAsync', this.allItem);
}
let itemList = await this.$importf(idName)
this.contracts.push({ value: this.allItem })
if (itemList && itemList.length > 0) {
this.tableHeads = itemList[0]
this.tabelBody = itemList
}
})
},
注意:如果多次重复上传change时间就会出问题,所以采用在click事件里面监听change事件