"xlsx": "^0.16.9"
npm install xlsx 版本我用的0.16.9,可以安装好后,在package.json文件中更改版本号后,再‘npm install’
组件
<template>
<span style="margin-right:10px">
<input class="input-file" type="file" @change="exportData"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<el-button type="primary" size="mini" icon="el-icon-upload" @click="btnClick">上传Excel表格数据</el-button>
</span>
</template>
<script>
import XLSX from 'xlsx'
export default {
name: "XlsxUpload",
data() {
return {}
},
methods: {
btnClick() {
document.querySelector('.input-file').click()
},
exportData(event) {
if (!event.currentTarget.files.length) {
return
}
const that = this
// 拿取文件对象
let f = event.currentTarget.files[0]
// 用FileReader来读取
let reader = new FileReader()
// 重写FileReader上的readAsBinaryString方法
FileReader.prototype.readAsBinaryString = function(f) {
let binary = ''
let wb // 读取完成的数据
let outdata // 你需要的数据
let reader = new FileReader()
reader.onload = function(e) {
// 读取成Uint8Array,再转换为Unicode编码(Unicode占两个字节)
let bytes = new Uint8Array(reader.result)
let length = bytes.byteLength
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
// 接下来就是xlsx了,具体可看api
wb = XLSX.read(binary, {
type: 'binary'
})
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
// 自定义方法向父组件传递数据
that.$emit('getResult', outdata)
}
reader.readAsArrayBuffer(f)
}
reader.readAsBinaryString(f)
}
}
}
</script>
<style scoped>
.input-file {
display: none;
}
</style>
使用组件
<template>
<div v-if="'超级管理员'===$store.getters.getUser.role ">
<xlsx-upload @getResult="getMyExcelData"></xlsx-upload>
<el-table
:data="tableData"
style="width: 100%"
:row-class-name="tableRowClassName">
<el-table-column
label="序号"
type="index"
width="80"
align="center">
</el-table-column>
<el-table-column
prop="username"
label="卡号"
width="180">
</el-table-column>
<el-table-column
prop="rawPassword"
label="卡密"
width="180">
</el-table-column>
<el-table-column
prop="productType"
label="型号"
width="180">
</el-table-column>
</el-table>
<el-button type="danger" @click="insertYourCardsToDatabase">提交到数据库</el-button>
</div>
</template>
<script>
import XlsxUpload from "@/views/accounting/XlsxUpload";
const {insertCustomCards} = require("@/api/login");
export default {
name: "UploadExcel",
components: {XlsxUpload},
data() {
return {
tableData: [{
username: '',
rawPassword: '',
productType: ''
}]
}
},
methods: {
getMyExcelData(data) {
// data 为读取的excel数据,在这里进行处理该数据
console.log(data)
this.tableData = data
},
insertYourCardsToDatabase() {
let JsonUsers = this.tableData;
//console.log(JsonUsers);
//console.log(JsonUsers[0].username)
if (JsonUsers[0].username === '') {
this.$message('请选择需要上传的文件');
return
}
insertCustomCards(JsonUsers).then((response) => {
console.log(response)
this.$alert('成功添加了' + response.data + '条数据\n' + '请在卡片管理页面查看', '成功', {
confirmButtonText: '好',
type: 'success',
callback: () => {
this.$router.push('/accounting/CardManage')
}
})
}).catch(() => {
this.$alert('数据错误,请检查卡号是否有重复', '出错了', {
confirmButtonText: '确定',
type: 'warning',
callback: () => {
this.$router.push('/accounting/CardManage')
}
})
})
},
tableRowClassName({row, rowIndex}) {
if (row.productType === 688) {
return 'warning-row';
} else if (row.productType === 1088) {
return 'success-row';
}
return '';
}
},
}
</script>
<style scoped>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
以上是上传自己电脑端的excel到服务端
导出:
const openFullScreen2FileOutput = (() => {
let loading = Loading.service({
lock: true,
text: '数据下载中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
setTimeout(() => {
loading.close();
}, 5000);
})
const fileOutputConfirm = (() => {
$confirm('导出本页文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
exportToExcel();
openFullScreen2FileOutput();
setTimeout(() => {
$message({
type: 'success',
message: '导出成功!'
})
}, 5200)
}).catch(() => {
$message({
type: 'info',
message: '已取消'
});
});
})
const exportToExcel = (() => {
let table = document.getElementById('table');
let workBook = XLSX.utils.table_to_book(table);
try {
XLSX.writeFile(workBook, 'yourFile.xlsx');
} catch (e) {
console.log(e);
}
})