Vue项目中excel导入功能实现
一、安装必要的插件
npm install xlsx -S
二、引入UploadExcel组件并注册为全局
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">
将文件拖入此处或
<el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
点击上传
</el-button>
</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>
.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>
注册成全局组件src/components/index.js
import UploadExcel from './UploadExcel'
export default {
// 插件的初始化, 插件给你提供的全局的功能, 都可以在这里配置
install(Vue) {
// 进行组件的全局注册
Vue.component('UploadExcel', UploadExcel) // 注册导入excel组件
}
}
main.js
文件中
// Components 为上面在 index.js 文件中默认导出的对象
import Components from './components'
Vue.use(Components) // 全局注册使用
三、使用–新建一个公共的导入页面并配置路由
src/views/import/index.vue
在页面中使用前面封装的excel上传组件,并补充导入成功后的回调函数
<template>
<!-- 使用全局注册的组件 -->
<upload-excel :on-success="handleSuccess" />
</template>
<script>
export default {
name: 'Import',
methods: {
// 转换导入的表格的信息
handleSuccess({ header, results }) {
console.log(header, results)
// header 标题
// 例 ['姓名','手机号']
// results excel表格的内容(每一行)
// 例 [ {'姓名':'小张', '手机号': '13712345678'}, {.....} ]
}
}
}
// excel导入插件本质:把excel经过分析转换成js能够识别的常规数据,拿到数据我们可以进行任何操作
</script>
src/router/index.js
添加一个静态路由
{
path: '/import',
component: Layout,
hidden: true, // 不显示到左侧菜单
children: [{
path: '',
component: () => import('@/views/import')
}]
}
页面效果图
此时,我们在此页面内就可以调用向后端提交数据的API接口,把转换后的表格数据对后端进行提交(数据的转换需要转换成和后端要求的格式一致的数据,详见后端提供的接口文档)
四、excel导入时存在时间日期变形的问题
从excel中读入的日期时间“变形”了
原因:excel内部进行特殊的编码
需要借助公式来进行还原。在src/utils/index.js
中定义如下
// 把excel文件中的日期格式的内容转回成标准时间
// https://blog.csdn.net/qq_15054679/article/details/107712966
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)
}