1.导入功能基本实现
1.1下载excel依赖包
npm install xlsx -S
1.2 封装组件?
?在src/components下面新建UploadExcel/index.vue组件?
<template>
<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">
Drop excel file here or
<el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
Browse
</el-button>
</div>
</div>
</template>
<script>
import XLSX from 'xlsx'
export default {
name: 'UploadExcel',
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>
.excel-upload-input{
display: none;
z-index: -9999;
}
.drop{
border: 2px dashed #bbb;
width: 600px;
height: 160px;
line-height: 160px;
margin: 0 auto;
font-size: 24px;
border-radius: 5px;
text-align: center;
color: #bbb;
position: relative;
}
</style>
1.3全局注册组件
import UploadExcel from './UploadExcel'
export default {
install(p) {
p.component(UploadExcel.name, UploadExcel)
}
}
?1.4 使用组件
使用后我们就会拿到一个基本的上传excel的基本结构? 如图??
?1.5 导入功能基本实现代码
<template>
<div>
<UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
</div>
</template>
<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
methods: {
beforeUpload(file) {
const isLt1M = file.size / 1024 / 1024 < 1
if (isLt1M) {
return true
}
this.$message({
message: 'Please do not upload files larger than 1m in size.',
type: 'warning'
})
return false
},
handleSuccess({ results, header }) {
/**
* results excel表格的内容
// [
{'姓名':'小张', '手机号': '13712345678'}
, {.....}
]
// 目标
// [ {'username':'小张','mobile': '13712345678'}, {.....} ]
*/
// 把一个对象数组中的每个对象的属性名,从中文改成英文
// 思路:对于原数组每个对象来说
// (1) 找出所有的中文key
// (2) 得到对应的英文key
// (3) 拼接一个新对象: 英文key:值
console.log(results, header)
const newArr = this.format(results, header)
// console.log(newArr)
this.doImport(newArr)
},
// 导入excel
format(result, header) {
const mapInfo = {
'入职日期': 'timeOfEntry',
'手机号': 'mobile',
'姓名': 'username',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName',
'聘用形式': 'formOfEmployment'
}
const arr = []
result.map(it => {
const enobj = {}
header.forEach(zhkey => {
const enkey = mapInfo[zhkey]
if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
enobj[enkey] = new Date(formatExcelDate(it[zhkey]))
} else {
enobj[enkey] = it[zhkey]
}
})
arr.push(enobj)
})
return arr
},
async doImport(newArr) {
try {
const res = await importEmployee(newArr)
console.log(res)
this.$message.success('批量导入成功')
this.$router.back()
} catch (error) {
console.log(error)
}
}
}
}
</script>
<style>
</style>
format函数的原理解析请移步到另一篇博客??干货大全_m0_52765288的博客-CSDN博客
1.6 formatExcel格式化excel的时间?
// 把excel文件中的日期格式的内容转回成标准时间
export function formatExcelDate(numb, format = '/') {
const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
time.setYear(time.getFullYear())
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() + ''
if (format && format.length === 1) {
return year + format + month + format + date
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}
1.7封装接口
/**
* @description: 导入excel
* @param {*} data
* @return {*}
*/
export function importEmployee(data) {
return request({
url: '/sys/user/batch',
method: 'post',
data
})
}
2.导出功能
2.1定义导出excel的方法
hExport() {
import('@/vendor/Export2Excel').then(async excel => {
// 发ajax请求,获取数据
const res = await getEmployeeList(this.paramsPage)
const list = res.data.rows
console.log('从后端获取的数据', list)
const { header, data } = this.formatData(list)
// excel表示导入的模块对象
console.log(header, data)
excel.export_json_to_excel({
// header: ['姓名', '工资'], // 表头 必填
header: header, // 表头 必填
data: data,
// data: [
// ['刘备11111111111111', 100],
// ['关羽', 500]
// ], // 具体数据 必填
filename: 'excel-list', // 文件名称
autoWidth: true, // 宽度是否自适应
bookType: 'xlsx' // 生成的文件类型
})
})
}
2.2 自定义导出格式
formatData(list) {
const map = {
'id': '编号',
'password': '密码',
'mobile': '手机号',
'username': '姓名',
'timeOfEntry': '入职日期',
'formOfEmployment': '聘用形式',
'correctionTime': '转正日期',
'workNumber': '工号',
'departmentName': '部门',
'staffPhoto': '头像地址'
}
console.log(list)
let header = []
// header = ['id', 'mobile', 'username', .....]
// data = [
// ['65c2', '1380000002', '管理员', ....],
// ['65c3', '1380000003', '孙财', ....],
// ]
let data = []
// 开始代码
// 找到一个元素
const one = list[0]
if (!one) {
return { header, data }
}
header = Object.keys(one).map(key => {
return map[key]
})
// data把list中每一个对象转成 对应的value数组
data = list.map(obj1 => {
// 把 Obj['formOfEmployment']: 1 , 2 ---> '正式', '非正式'
const key = obj1['formOfEmployment'] // 1, 2
obj1['formOfEmployment'] = obj[key] // hireTypEnmu:{1:'正式', '2':'非正式' }
return Object.values(obj1)
})
return { header, data }
},
formatData函数解析请移步另一篇代码? ? 干货大全_m0_52765288的博客-CSDN博客
|