1.excel导入功能需要使用npm包xlsx,所以需要安装xlsx插件
yarn add xlsx
2.封装一个导入组件UploadExcel.vue
<template>
<div class="upload-excel">
<div class="btn-upload">
<el-button :loading="loading" size="mini" type="primary" @click="handleUpload">
点击上传
</el-button>
</div>
<input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
<div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
<i class="el-icon-upload" />
<span>将文件拖到此处</span>
</div>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
props: {
beforeUpload: Function, // eslint-disable-line
onSuccess: Function// eslint-disable-line
},
data() {
return {
loading: false,
excelData: {
header: null,
results: null
}
}
},
methods: {
generateData({ header, results }) {
this.excelData.header = header
this.excelData.results = results
this.onSuccess && this.onSuccess(this.excelData)
},
handleDrop(e) {
e.stopPropagation()
e.preventDefault()
if (this.loading) return
const files = e.dataTransfer.files
if (files.length !== 1) {
this.$message.error('Only support uploading one file!')
return
}
const rawFile = files[0] // only use files[0]
if (!this.isExcel(rawFile)) {
this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
return false
}
this.upload(rawFile)
e.stopPropagation()
e.preventDefault()
},
handleDragover(e) {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
},
handleUpload() {
this.$refs['excel-upload-input'].click()
},
handleClick(e) {
const files = e.target.files
const rawFile = files[0] // only use files[0]
if (!rawFile) return
this.upload(rawFile)
},
upload(rawFile) {
this.$refs['excel-upload-input'].value = null // fix can't select the same excel
if (!this.beforeUpload) {
this.readerData(rawFile)
return
}
const before = this.beforeUpload(rawFile)
if (before) {
this.readerData(rawFile)
}
},
readerData(rawFile) {
this.loading = true
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = e => {
const data = e.target.result
const workbook = XLSX.read(data, { type: 'array' })
const firstSheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[firstSheetName]
const header = this.getHeaderRow(worksheet)
const results = XLSX.utils.sheet_to_json(worksheet)
this.generateData({ header, results })
this.loading = false
resolve()
}
reader.readAsArrayBuffer(rawFile)
})
},
getHeaderRow(sheet) {
const headers = []
const range = XLSX.utils.decode_range(sheet['!ref'])
let C
const R = range.s.r
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
/* find the cell in the first row */
let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
headers.push(hdr)
}
return headers
},
isExcel(file) {
return /\.(xlsx|xls|csv)$/.test(file.name)
}
}
}
</script>
<style scoped lang="scss">
.upload-excel {
display: flex;
justify-content: center;
margin-top: 100px;
.excel-upload-input{
display: none;
z-index: -9999;
}
.btn-upload , .drop{
border: 1px dashed #bbb;
width: 350px;
height: 160px;
text-align: center;
line-height: 160px;
}
.drop{
line-height: 80px;
color: #bbb;
i {
font-size: 60px;
display: block;
}
}
}
</style>
样式效果如图:
3.封装完成后就可以使用该组件
<template>
// 设置on-success属性 值为一个方法
<upload-excel :on-success="success" />
</template>
<script>
export default {
methods: {
async success({ header, results }) {
// 接收两个参数 header:导入的表头数组 results:导入的内容数组
const userRelations = {
'入职日期': 'timeOfEntry',
'手机号': 'mobile',
'姓名': 'username',
'转正日期': 'correctionTime',
'工号': 'workNumber'
}
const newArr = []
// results 返回的是一个数组 且属性名是中文 我们需要处理成英文进行调用接口
results.forEach(item => {
const userInfo = {}
// 循环拿到属性值 ['入职日期',手机号','姓名','转正日期','工号']的数组 key就是每一项
Object.keys(item).forEach(key => {
// 假如得到的是时间字段 需要二次处理
if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
userInfo[userRelations[key]] = new Date(this.formatDate(item[key], '/')) // 只有这样, 才能入库
} else {
// 循环拿到的属性值数组 给空对象添加英文属性和对应的值
userInfo[userRelations[key]] = item[key]
}
})
newArr.push(userInfo)
})
// 处理完成之后就能得到一个新的 newArr 数组
// 利用newArr就可以调后端接口
......
},
// 这里提供一个 处理excel内的日期字段函数 js 不能识别excel的日期格式
formatDate(numb, format) {
const time = new Date((numb - 1) * 24 * 3600000 + 1)
time.setYear(time.getFullYear() - 70)
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() - 1 + ''
if (format && format.length === 1) {
return year + format + month + format + date
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}
}
}
</script>
4. 实现导出功能
Excel 的导入导出都是依赖于js-xlsx来实现的。
在 js-xlsx的基础上又封装了Export2Excel.js来方便导出数据
所以你先需要安装如下命令:
yarn add file-saver
yarn add script-loader -D
由于js-xlsx体积还是很大的,导出功能也不是一个非常常用的功能,所以使用的时候建议使用懒加载。使用方法如下:
import('@/vendor/Export2Excel').then(excel => {
excel.export_json_to_excel({
header: tHeader, //表头 必填
data, //具体数据 必填
filename: 'excel-list', //非必填
autoWidth: true, //非必填
bookType: 'xlsx' //非必填
})
})
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| header | 导出数据的表头 | Array | / | [] |
| data | 导出的具体数据 | Array | / | [[]] |
| filename | 导出文件名 | String | / | excel-list |
| autoWidth | 单元格是否要自适应宽度 | Boolean | true / false | true |
| bookType | 导出文件类型 | String | xlsx, csv, txt, more | xlsx |
<template>
<el-button size="small" type="danger" @click="exportData">导出Excel</el-button>
</template>
<script>
methods:{
exportData() {
// 因为数据中的key是英文,想要导出的表头是中文的话,需要将中文和英文做对应
const headers = {
'手机号': 'mobile',
'姓名': 'username',
'入职日期': 'timeOfEntry',
'聘用形式': 'formOfEmployment',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName'
}
import('@/vendor/Export2Excel').then(async excel => {
// 调用请求员工列表的接口 获取到全部数据
const { rows } = 调用请求员工列表的接口 获取到全部数据
// 传入 headers (定义对应关系) rows (全部员工数据)
const data = this.formatJson(headers, rows)
// 定义复杂表头 一级表头
const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
// 合并表头
const merges = ['A1:A2', 'B1:F1', 'G1:G2']
excel.export_json_to_excel({
header: Object.keys(headers), // 导出表头
data: data, // 导出内容 格式为 [[]]
filename: '员工信息表', // 导出 excel文件名
autoWidth: true, // 自适应宽度
bookType: 'xlsx', // 导出文件格式 默认 xlsx
multiHeader,
merges
})
})
}
// 定义处理导出data数据的处理函数 接收对应关系的对象和需要处理的数组
formatJson(headers, rows) {
return rows.map(item => {
return Object.keys(headers).map(key => {
// 判断如果是时间字段需要格式化一下 根据上面提示的处理时间函数格式化
if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
return formatDate(item[headers[key]])
}
return item[headers[key]]
})
})
}
}
</script>