当前位置:网站首页>Upload excel file
Upload excel file
2022-07-24 07:03:00 【MMNHD】

<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>
// Core parsing tripartite plug-in The function is to put excel File resolved to js Format
// xlsx The library has been updated The way of import has changed
// solve : Change the import method to the latest import
import * as XLSX from 'xlsx'
export default {
// It is allowed to pass in parameters
props: {
// The callback function before parsing effect : Yes excel Check the file Like size Format
beforeUpload: Function, // eslint-disable-line
// Callback function automatically executed after successful parsing Type function effect : Get excel The parsed data
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>

/**
* @description: Get the header data and table data when exporting
* @param {*} { sourceData: The source data returned by the backend ,header: Because of the correspondence in the table header }
* @return {*}
*/
// Handle... In function key Judge if it is the current form of employment Do some processing through enumeration Back to Chinese
// Enumerating handler functions according to 1/2 Return to formal or informal
function transEmployment(value) {
const TYPES = {
1: ' formal ',
2: ' informal '
}
return TYPES[value]
}
export function getExportData(sourceData, headerRelation) {
const data = sourceData.map(item => {
const arr = []
Object.values(headerRelation).forEach(key => {
// Key points : Put all the value Without any processing, it is directly thrown into the array Lead to excel It's the source data
// If it is the current form of employment to be handled Just convert it first and then add it to the array
if (key === 'formOfEmployment') {
const formatValue = transEmployment(item[key])
arr.push(formatValue)
} else {
arr.push(item[key])
}
})
return arr
})
return {
data
}
}
/**
* @description: Get the interface data after processing during import
* @param {*} results
* @return {*}
*/
export function getImportJsData(results, headerRelation) {
const newArr = []
// All Chinese key Convert to English key Then add to the new array
results.forEach(item => {
const map = {}
Object.keys(item).forEach(key => {
map[headerRelation[key]] = item[key]
})
newArr.push(map)
})
// Time processing
newArr.forEach(item => {
Object.keys(item).forEach(key => {
if (key === 'timeOfEntry') {
item[key] = new Date(formatDate(item[key], '/'))
}
})
})
return newArr
}
export function 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 < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

<template> <div class="app-container"> <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" /> <el-table :data="tableData" border highlight-current-row style="width: 100%; margin-top: 20px" > <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" /> </el-table> </div> </template> <script> import UploadExcelComponent from '@/components/UploadExcel/index.vue' import { getImportJsData } from '@/utils/excel' import { fetchImportExcel } from '@/api/employee' export default { name: 'UploadExcel', components: { UploadExcelComponent }, data () { return { tableData: [], tableHeader: [] } }, methods: { // Parse the check function executed before // If it passes the verification inside the function such as return true // Otherwise, return false When return The value of is false The execution of parsing logic will be stopped beforeUpload (file) { // file excel File object console.log(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 }, // The callback success function executed after parsing async handleSuccess ({ results, header }) { // results: An array of objects Table body data // header: Array Table body data console.log(results, header) // Convert the data produced by the plug-in into the format required by the interface getImportJsData const headerRelation = { ' full name ': 'username', ' cell-phone number ': 'mobile', ' Date of entry ': 'timeOfEntry', ' Job number ': 'workNumber', ' Form of employment ': 'formOfEmployment', ' department ': 'departmentName' } const result = getImportJsData(results, headerRelation) console.log(result) await fetchImportExcel(result) this.$message.success(' Successful import ') // Jump back this.$router.back() this.tableData = results this.tableHeader = header } } } </script>
边栏推荐
猜你喜欢

STM32H750VBT6驱动程控增益放大模块PGA113——基于CubeMX的Hal库

《大厂面试》之JVM篇21问与答

Redis 分片集群

Esp32 ultra detailed learning record: NTP synchronization time

UE4/5 无法打开文件“xxx.generated.h”(Cannot open file xxx.generated.h)的解决方法总结

Create WPF project

Sealos 打包部署 KubeSphere 容器平台

OSS authorizes a single bucket permission

tensorflow scatter_nd函数

Redis 主从机制
随机推荐
OWASP TOP10 penetration test
(笔记整理未完成)【图论:求单源最短路径】
Tensorflow Einstein function
2022-07-22 mysql/stonedb parallel hashjoin memory usage analysis
js和ts学习总结
PyTorch 深度学习实践 第10讲/作业(Basic CNN)
不去和谁比较,只需做好自己
[learning notes] Web page rendering process
Input some data and find the maximum output. (keyboard and file reading)
【C语言】操作符详解(深入理解+整理归类)
MySQL gets the self incrementing line mark (different from MySQL version)
SPI——发送16位和8位数据
After grouping, return to the last record group in each group_ Use of concat
《大厂面试》之JVM篇21问与答
Penetration learning - SQL injection - shooting range - installation and bypass experiment of safety dog (it will be updated later)
处理树形结构数据
[C language] operator details (in-depth understanding + sorting and classification)
(static, dynamic, file) three versions of address book
【杂论:离散化】
渗透学习-SQL注入篇-靶场篇-安全狗的安装与绕过实验(后续还会更新)