vue 导入excle,可以预览

13 篇文章 0 订阅
10 篇文章 0 订阅

导入exclel,数据转成json,可以预览
html部分

<div>
   <div>
        <el-button :disabled="isReadonly" size="mini" type="primary" @click="onImport()">{{ _btnName }}</el-button>
        <el-button :disabled="isReadonly" v-show="preview&&isPreview" size="mini" type="primary" @click="onPreview()">{{ gBtnPreview }}</el-button>
        <input type="file" :id="id" :accept="accept" @change="onChangeImport()" style="display:none;" ref="inputer"/>
        <span>{{msg}}<span>
   </div>
   <el-dialog append-to-body top="5%" title="Preview" :close-on-click-modal="false" custom-class="dialogForm" width="85%" v-if="show" :visible.sync="show" :before-close="beforeClose">
    <el-table :data="table.tableData" class="table-scroll" highlight-current-row border stripe style="width: 100%;">
        <el-table-column v-for="v in table.tableHeader" :prop="v.replace(/\\./g, \'\')" :label="v">
        </el-table-column>
    </el-table>
   </el-dialog>
</div>

js部分

data: function () {
            return {
                wb: null, // 读取完成的数据
                rABS: false,
                id: '_' + new Date().getUTCMilliseconds(),
                table: {
                    tableData: [],
                    tableHeader: []
                },
                _btnName: '',
                msg: '',
                isPreview: false,
                show: false,
                accept: '.xlsx,.xls,.csv'
            };
        },
        props: {
            size: {
                type: String,
                default: '2'
            },
            btnName: {
                type: String,
                default: null
            },
            preview: {
                type: Boolean,
                default: false
            },
            isReadonly: {
                type: Boolean,
                default: false
            }
        },
        created: function () {
            if (this.btnName) {
                this._btnName = this.btnName;
            } else {
                this._btnName ='excle';
            }
        },
        methods: {
            onImport: function () {
                this.clearAllData();
                document.getElementById(this.id).click()
            },
            onPreview: function () {
                if (this.preview) {
                    this.show = true;
                }
            },
            onChangeImport: function () {
                var inputDOM = this.$refs.inputer,
                    _this = this;
                if (!inputDOM) {
                    return;
                }

                var f = inputDOM.files[0];
                if (!this.beforeAvatarUpload(f)) {
                    return;
                }
                var reader = new FileReader();
                reader.onload = function () {
                    if (reader.result) {
                        reader.content = reader.result;
                    }
                    var data = reader.content;
                    if (_this.rABS) {
                        _this.wb = XLSX.read(btoa(fixdata(data)), { // 手动转化
                            type: 'base64'
                        });
                    } else {
                        _this.wb = XLSX.read(data, {
                            type: 'binary'
                        });
                    }
                    var j = XLSX.utils.sheet_to_json(_this.wb.Sheets[_this.wb.SheetNames[0]]);
                    if (j) {
                        // console.log(_this.xlsxArrToTableArr(j));
                        if (_this.preview) {
                            _this.show = true;
                        }
                        _this.msg = f.name;
                        _this.table = _this.xlsxArrToTableArr(j);
                        _this.isPreview = true;
                        _this.$emit('select', _this.table);
                    }
                    // var str = JSON.stringify()
                    // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                    // wb.Sheets[Sheet名]获取第一个Sheet的数据
                };
                if (_this.rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            },
            xlsxArrToTableArr: function (xlsxArr) {
                var tableArr = [],
                    length = 0,
                    maxLength = 0,
                    maxLengthIndex = 0;
                xlsxArr.forEach(function (item, index) {
                    length = Object.keys(item).length
                    if (maxLength < length) {
                        maxLength = length
                        maxLengthIndex = index
                    }
                })
                var tableHeader = Object.keys(xlsxArr[maxLengthIndex]),
                    rowItem = {};
                xlsxArr.forEach(function (item) {
                    rowItem = {}
                    for (var i = 0; i < maxLength; i++) {
                        rowItem[tableHeader[i]] = item[tableHeader[i]] || ''
                    }
                    tableArr.push(rowItem)
                })
                // 去除点.
                tableArr.forEach(function (item) {
                    for (var key in item) {
                        var rename = key.replace(/\./g, '')
                        item[rename] = item[key]
                    }
                })
                return {
                    tableHeader: tableHeader,
                    tableData: tableArr
                }
            },
            clearAllData: function () {
                document.getElementById(this.id).value = null
                this.table = {
                    tableData: [],
                    tableHeader: []
                }
                this.isPreview = false;
                this.msg = '';
                this.wb = null;
            },
            fixdata: function (data) { // 文件流转BinaryString
                var o = '',
                    l = 0,
                    w = 10240;
                for (; l < data.byteLength / w; ++l) {
                    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                }
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            },
            beforeClose: function () {
                this.show = false;
                // this.clearAllData();
            },
            beforeAvatarUpload: function (file) {
                var isLt = file.size / 1024 / 1024 < parseInt(this.size);
                if (!isLt) {
                    this.$message.error('Uploading files cannot exceed ' + this.size + 'MB!');
                }
                return isLt;
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值