npm install xlsx --save
<!-- 导入导出组件(纯前端) -->
<template>
<span>
<input type="file" @change="importFile(this)" id="imFile" style="display:none;"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
<a id="downlink"></a>
<span @click="downloadFile">
<slot name="export">
<el-button class="button">导出</el-button>
</slot>
</span>
<span @click="uploadFile">
<slot name="import">
<el-button class="button">导入</el-button>
</slot>
</span>
<!-- 错误信息提示 -->
<el-dialog title="提示" v-model="errorDialog" size="tiny">
<span>{{ errorMsg }}</span>
<span slot="footer" class="dialog-footer">
<el-button type="primary" @click="errorDialog=false">确认</el-button>
</span>
</el-dialog>
</span>
</template>
<script>
var XLSX = require('xlsx')
export default {
name: 'ProgExportImport',
data() {
return {
fullscreenLoading: false,
imFile: '',
outFile: '',
errorDialog: false,
errorMsg: '',
excelTitle: {},
excelData: []
}
},
props: {
setExportData: {
type: Function,
default: function() {
console.warn('未传递获取excel导出数据方法')
}
},
getImportData: {
type: Function,
default: function() {
console.warn('未传递设置excel导入数据方法')
}
}
},
mounted() {
this.imFile = document.getElementById('imFile')
this.outFile = document.getElementById('downlink')
},
methods: {
uploadFile: function() {
this.imFile.click()
},
downloadFile: function() {
let exportData = this.setExportData()
this.excelTitle = exportData.excelTitle
this.excelData = exportData.excelData
let data = [{},{}]
for (let k in this.excelData[0]) {
if (this.excelData[0].hasOwnProperty(k)) {
data[0][k] = k
data[1][k] = this.excelTitle[k]
}
}
data = data.concat(this.excelData)
this.downloadExl(data, exportData.excelName || '导出文件')
},
importFile: function() {
this.fullscreenLoading = true
let obj = this.imFile
if (!obj.files) {
this.fullscreenLoading = false
return
}
var f = obj.files[0]
var reader = new FileReader()
let $t = this
reader.onload = function(e) {
var data = e.target.result
if ($t.rABS) {
$t.wb = XLSX.read(btoa(this.fixdata(data)), {
type: 'base64'
})
} else {
$t.wb = XLSX.read(data, {
type: 'binary'
})
}
let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]])
$t.dealFile($t.analyzeData(json))
}
if (this.rABS) {
reader.readAsArrayBuffer(f)
} else {
reader.readAsBinaryString(f)
}
},
downloadExl: function(json, downName, type) {
let keyMap = []
for (let k in json[0]) {
if (json[0].hasOwnProperty(k)) {
keyMap.push(k)
}
}
let tmpdata = []
json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
v: v[k] || '',
position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
}))).reduce((prev, next) => prev.concat(next)).forEach(function(v) {
tmpdata[v.position] = {
v: v.v
}
})
let outputPos = Object.keys(tmpdata)
let tmpWB = {
SheetNames: ['sheet'],
Sheets: {
'sheet': Object.assign({},
tmpdata,
{
'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1]
})
}
}
let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
{ bookType: (type || 'xlsx'), bookSST: false, type: 'binary' }
))], {
type: ''
})
var href = URL.createObjectURL(tmpDown)
this.outFile.download = downName + '.xlsx'
this.outFile.href = href
this.outFile.click()
setTimeout(function() {
URL.revokeObjectURL(tmpDown)
}, 100)
},
analyzeData: function(data) {
data.splice(0, 1)
return data
},
dealFile: function(data) {
this.imFile.value = ''
this.fullscreenLoading = false
if (data.length <= 0) {
this.errorDialog = true
this.errorMsg = '请导入正确信息'
} else {
this.excelData = data
this.getImportData(data)
}
},
s2ab: function(s) {
var buf = new ArrayBuffer(s.length)
var view = new Uint8Array(buf)
for (var i = 0; i !== s.length; ++i) {
view[i] = s.charCodeAt(i) & 0xFF
}
return buf
},
getCharCol: function(n) {
let s = ''
let m = 0
while (n > 0) {
m = n % 26 + 1
s = String.fromCharCode(m + 64) + s
n = (n - m) / 26
}
return s
},
fixdata: function(data) {
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
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
<export-import :set-export-data="setExportData" :get-import-data="getImportData">
<template slot="export">
<el-button type="primary" plain size="mini">导出</el-button>
</template>
<template slot="import">
<el-button type="primary" plain size="mini">导入</el-button>
</template>
</export-import>
setExportData() {
return {
excelTitle: {
code: "编号",
name: "名称",
},
excelData: [],
excelName: "导出",
};
},
getImportData(data) {
console.log(data);
},