一 、导入
- Exel的导入需要先转换成xlsx格式 可以通过 npm i xlsx file-saver -S 下载依赖包 而后直接去git上搜 花裤衩 用他的UploadExcel 组件 -.- 这样就可以轻松很多啦
- 减UploadExcel 引入components 下的index.js 然后去main中进行全局注册 上代码 (也可以直接引入需要使用的文件夹)
import UploadExcel from '@/components/UploadExcel/index.vue'
export default { install(Vue) { Vue.component('UploadExcel', UploadExcel) } 4. 封装组件
- 在路由中添加自己准备的导入页面组件
- 给导入按钮绑定一个事件 点击后跳转到导入页面
- 在导入页面引入UploadExcel 绑定 :on-success="UploadExcel"
- async UploadExcel(data)
实现导入:
async UploadExcel(data){
//使用map 方法 对数据进行改造
const result = data.results(这是接口中的数组名).map(item=>{
// 返回改造好的数据
return this.zhToEn(item) // 实参 接收接口中的数据
})
// 改造数据完成后调用接口
await importEmployee'这个接口是获取所有数据的接口 看后台情况'(result)
this.$router.back() // 返回上一页
}
// 行参 接收 传过来的数据
zhToEn(item){
const obj = {}
const user = { // 自己需要的数据
'手机号': 'mobile',
'姓名': 'username',
'入职日期': 'timeOfEntry',
'转正日期': 'correctionTime',
'工号': 'workNumber'
}
// item 接收到 接口中的数据
for (const key in item) {
// 日期需要格式化
if(key === '入职日期' || key === '转正日期'){
obj[user[key]] = this.formatExcelDate(item[key])
}else {
obj[user[key]] = item[key]
}
}
// 返回改造好的数据
return obj
}
下面是格式日期的代码:
/**
* 格式化Excel表中存储的年月日日期
* @param {number} num - excel存储的数字
* @param {string} [format = '-'] - 年月日的间隔符,默认为'-'
* @returns {string} 格式化后的日期
*/
formatExcelDate(num, format = '-') {
if (!/^\d+$/.test(num)) return
num = parseInt(num)
let millisecond = 0 // 转化后的毫秒数
if (num > 60) { // 对大于60的日期进行减1处理
millisecond = (num - 25568 - 1) * 3600 * 24 * 1000
} else {
millisecond = (num - 25568) * 3600 * 24 * 1000
}
const date = new Date(millisecond) // 根据转化后的毫秒数获取对应的时间
const yy = date.getFullYear()
const m = date.getMonth() + 1
const mm = m >= 10 ? m : '0' + m
const d = date.getDate()
const dd = d >= 10 ? d : '0' + d
return yy + format + mm + format + dd // 返回格式化后的日期
}
}
2. 导出
async exportFn(){
const res = await getUserList({ // 封装的后端接口
page:1, // 1页
total:this.total // 总数据条数
})
const header = ['手机号', '姓名', '入职日期', '转正日 期', '工号'] // 需要从后端获取的数据
const data = res.rows(后台数据).map(item=>{
// map 可以改造原数组并且不会影响原数组的数据
return this.objToArr(item)
// 下载file-saver 调用里面的 export_json_to_excel实 现导出
export_json_to_excel({
header:header,
data:data
})
})
}
// 形参 接收 传递过来的后台数据
objToArr(item){
const arr = [] // 用于接收数据
// 自己需要的数据
const user = {
mobile: '手机号',
username: '姓名',
timeOfEntry: '入职日期',
correctionTime: '转正日期',
workNumber: '工号'
}
for(const key in user){
// 对日期 进行格式化 加入定义的空数组
if(key ==='timeOfEntry' || key ==='correctionTime') {
arr.push(formatDate(item[key],'yyyy/MM/dd'))
}else{
arr.push(item[key])
}
}
}