前端导入导出excel表方法
安装
npm install xlsx
<script lang="javascript" src="dist/xlsx.full.min.js"></script>
<template> <div @drop="_drop" @dragenter="_suppress" @dragover="_suppress" class="sheet-upload"> <div class="row"> <div class="col-xs-12"> <form class="form-inline"> <div class="form-group"> <Upload multiple type="drag" :disabled="isDisabledUpload" :before-upload="beforeUpload" action="/" > <slot></slot> </Upload> </div> </form> </div> </div> </div> </template> <script> import XLSX from 'xlsx' const make_cols = refstr => Array(XLSX.utils.decode_range(refstr).e.c + 1) .fill(0) .map((x, i) => ({ name: XLSX.utils.encode_col(i), key: i })) const _SheetJSFT = ['xlsx', 'csv'] .map(function(x) { return '.' + x }) .join(',') export default { props: { isDisabled: { type: Boolean, default: function() { return false } } }, data() { return { data: [], cols: [ { name: 'A', key: 0 }, { name: 'B', key: 1 }, { name: 'C', key: 2 }, { name: 'D', key: 3 }, { name: 'E', key: 4 }, { name: 'F', key: 5 }, { name: 'G', key: 6 } ], SheetJSFT: _SheetJSFT, isDisabledUpload: true } }, watch: { isDisabled: { handler(newId, oldId) { this.isDisabledUpload = newId }, immediate: true } }, methods: { beforeUpload(file) { this._file(file) return false }, uploadHandler() { this.$refs.FileInput.click() }, _suppress(evt) { evt.stopPropagation() evt.preventDefault() }, _drop(evt) { evt.stopPropagation() evt.preventDefault() const files = evt.dataTransfer.files if (files && files[0]) this._file(files[0]) }, _change(evt) { const files = evt.target.files if (files && files[0]) this._file(files[0]) }, _export(evt) { /* convert state to workbook */ const ws = XLSX.utils.json_to_sheet(this.data) const wb = XLSX.utils.book_new() XLSX.utils.book_append_sheet(wb, ws, 'SheetJS') /* generate file and send to client */ XLSX.writeFile(wb, 'sheetjs.xlsx') }, _file(file) { /* Boilerplate to set up FileReader */ const reader = new FileReader() reader.onload = e => { /* Parse data */ const bstr = e.target.result const wb = XLSX.read(bstr, { type: 'binary' }) /* Get first worksheet */ const wsname = wb.SheetNames[0] const ws = wb.Sheets[wsname] /* Convert array of arrays */ const data = XLSX.utils.sheet_to_json(ws) // let sheetData = [] // data.forEach(item => { // if (item.length > 0) { // sheetData.push(item) // } // }) this.data = data this.cols = make_cols(ws['!ref']) this.$emit('on-success', data) } reader.readAsBinaryString(file) } }, created() { this.isDisabledUpload = this.isDisabled } } </script> <style lang="less" scoped> .sheet-upload { .form-control { display: none; } } </style>