May 30, 2021 Article blog
The contents of the Excel table are output with js
Use js to get the data in the Excel table in the vue project
cnpm i xlsx
import XLSX from 'xlsx'
function get_header_row (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 */
var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
var hdr = 'UNKNOWN ' + C // <-- replace with your desired default
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
headers.push(hdr)
}
return headers
}
const read = (data, type) => {
const workbook = XLSX.read(data, { type: type })
const firstSheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[firstSheetName]
const header = get_header_row(worksheet)
const results = XLSX.utils.sheet_to_csv(worksheet)
return { header, results }
}
export { read }
Step 3: Use in the project to get the data in the table
<template>
<div>
<el-button class="exportExcel"
@click="exportExcel">导入</el-button>
<input type="file"
ref="keyWordData"
@change='handleBeforeUpload'>
</div>
</template>
<script>
import { read } from '@/utils/excel'
export default {
data () {
return {
allData: [],
}
},
methods: {
exportExcel () {
this.$refs['keyWordData'].click()
},
handleBeforeUpload (event) {
let file = event.target.files[0]
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = e => {
const data = e.target.result
const { results } = read(data, 'array')
if (results) {
let arr = this.$CommUtils.deepClone(results.split('\n'))
arr = arr.filter(item => {
return item
})
this.keyWordData = arr
console.log(arr)
}
}
},
},
}
</script>
Arr is an array, each element is a string, separated by a comma, and if you want to get a point of it, you need to use sprit to cut into an array, and then create a new empty array to push the data you need.
Recommended lessons: Vue 3.0 Comprehensive analysis of new features (at the forefront of technology), small white school front end: Vue.js 2.0 advanced