|
| 1 | +<template> |
| 2 | + <div> |
| 3 | + <el-button :loading="loading" type="primary" @click="handleUpload">select excel file</el-button> |
| 4 | + <input id="excel-upload-input" type="file" accept=".xlsx, .xls" class="c-hide" @change="handkeFileChange"> |
| 5 | + </div> |
| 6 | +</template> |
| 7 | + |
| 8 | +<script> |
| 9 | +import XLSX from 'xlsx' |
| 10 | +
|
| 11 | +export default { |
| 12 | + data() { |
| 13 | + return { |
| 14 | + loading: false, |
| 15 | + excelData: { |
| 16 | + header: null, |
| 17 | + results: null |
| 18 | + } |
| 19 | + } |
| 20 | + }, |
| 21 | + methods: { |
| 22 | + generateDate({ header, results }) { |
| 23 | + this.excelData.header = header |
| 24 | + this.excelData.results = results |
| 25 | + this.loading = false |
| 26 | + this.$emit('on-selected-file', this.excelData) |
| 27 | + }, |
| 28 | + handleUpload() { |
| 29 | + document.getElementById('excel-upload-input').click() |
| 30 | + }, |
| 31 | + handkeFileChange(e) { |
| 32 | + this.loading = true |
| 33 | + const files = e.target.files |
| 34 | + const itemFile = files[0] // only use files[0] |
| 35 | + const reader = new FileReader() |
| 36 | + reader.onload = e => { |
| 37 | + const data = e.target.result |
| 38 | + const fixedData = this.fixdata(data) |
| 39 | + const workbook = XLSX.read(btoa(fixedData), { type: 'base64' }) |
| 40 | + const firstSheetName = workbook.SheetNames[0] |
| 41 | + const worksheet = workbook.Sheets[firstSheetName] |
| 42 | + const header = this.get_header_row(worksheet) |
| 43 | + const results = XLSX.utils.sheet_to_json(worksheet) |
| 44 | + this.generateDate({ header, results }) |
| 45 | + } |
| 46 | + reader.readAsArrayBuffer(itemFile) |
| 47 | + }, |
| 48 | + fixdata(data) { |
| 49 | + let o = '' |
| 50 | + let l = 0 |
| 51 | + const w = 10240 |
| 52 | + for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w))) |
| 53 | + o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w))) |
| 54 | + return o |
| 55 | + }, |
| 56 | + get_header_row(sheet) { |
| 57 | + const headers = [] |
| 58 | + const range = XLSX.utils.decode_range(sheet['!ref']) |
| 59 | + let C |
| 60 | + const R = range.s.r /* start in the first row */ |
| 61 | + for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */ |
| 62 | + var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */ |
| 63 | + var hdr = 'UNKNOWN ' + C // <-- replace with your desired default |
| 64 | + if (cell && cell.t) hdr = XLSX.utils.format_cell(cell) |
| 65 | + headers.push(hdr) |
| 66 | + } |
| 67 | + return headers |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | +</script> |
| 72 | + |
| 73 | +<style scoped> |
| 74 | +#excel-upload-input{ |
| 75 | + display: none; |
| 76 | + z-index: -9999; |
| 77 | +} |
| 78 | +</style> |
0 commit comments