將Excel表格的內容用js進行輸出
問題:
在vue項目中使用js獲取Excel表格里面的數(shù)據(jù)
解決方法:
第一步:下載插件
cnpm i xlsx
第二步:新建一個js文件,將方法進行寫入,并導出
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 }
?第三步:在項目里使用,獲取到表格里的數(shù)據(jù)
<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是一個數(shù)組,每個元素是一個字符串,是用逗號分隔的,如果想得到其中的某個點,需要使用split進行切割成數(shù)組,然后再新建一個空數(shù)組,把需要的數(shù)據(jù)來進行push。
推薦好課:Vue 3.0 新特性全面解析(走在技術前沿)、小白學前端:Vue.js 2.0進階