关于javascript:vue的导入和导出简洁好用

9次阅读

共计 5284 个字符,预计需要花费 14 分钟才能阅读完成。

1. 我的项目 npm i xlsx –save
2. 将导入导出性能封装成组件
<template>
    <div>
        <a id="downlink"></a>
        <el-button class="button" @click="downloadFile(excelData['results'])"> 导出 </el-button>
        <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick" />
        <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
            Drop excel file here or
            <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">Browse</el-button>
        </div>
    </div>
</template>

<script>
import XLSX from 'xlsx';

export default {
    props: {
        beforeUpload: Function, // eslint-disable-line
        onSuccess: Function // eslint-disable-line
        
    },
    data() {
        return {
            loading: false,
            excelData: {
                header: null,
                results: null
            },
            outFile: null
        };
    },
    mounted() {this.outFile = document.getElementById('downlink');
    },
    methods: {generateData({ header, results}) {console.log(results)
            this.excelData.header = header;
            this.excelData.results = results;
            this.onSuccess && this.onSuccess(this.excelData);
        },
        handleDrop(e) {e.stopPropagation();
            e.preventDefault();
            if (this.loading) return;
            const files = e.dataTransfer.files;
            if (files.length !== 1) {this.$message.error('Only support uploading one file!');
                return;
            }
            const rawFile = files[0]; // only use files[0]

            if (!this.isExcel(rawFile)) {this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files');
                return false;
            }
            this.upload(rawFile);
            e.stopPropagation();
            e.preventDefault();},
        handleDragover(e) {e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
        },
        handleUpload() {this.$refs['excel-upload-input'].click();},
        handleClick(e) {
            const files = e.target.files;
            const rawFile = files[0]; // only use files[0]
            if (!rawFile) return;
            this.upload(rawFile);
        },
        upload(rawFile) {this.$refs['excel-upload-input'].value = null; // fix can't select the same excel

            if (!this.beforeUpload) {this.readerData(rawFile);
                return;
            }
            const before = this.beforeUpload(rawFile);
            if (before) {this.readerData(rawFile);
            }
        },
        readerData(rawFile) {console.log(rawFile);
            this.loading = true;
            return new Promise((resolve, reject) => {const reader = new FileReader();
                reader.onload = e => {
                    const data = e.target.result;
                    const workbook = XLSX.read(data, { type: 'array'});
                    const firstSheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[firstSheetName];
                    const header = this.getHeaderRow(worksheet);
                    const results = XLSX.utils.sheet_to_json(worksheet);
                    this.generateData({header, results});
                    this.loading = false;
                    resolve();};
                reader.readAsArrayBuffer(rawFile);
            });
        },
        getHeaderRow(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 */
                const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R})];
                /* find the cell in the first row */
                let hdr = 'UNKNOWN' + C; // <-- replace with your desired default
                if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
                headers.push(hdr);
            }
            return headers;
        },
        isExcel(file) {return /\.(xlsx|xls|csv)$/.test(file.name);
        },
        
        
        
        // 导出相干的办法
        downloadFile: function(rs) {
            // 点击导出按钮
            let data = [{}];
            for (let k in rs[0]) {data[0][k] = k;
            }
            data = data.concat(rs);
            this.downloadExl(data, '菜单');
        },
        
        downloadExl: function(json, downName, type) {
            // 导出到 excel
            let keyMap = []; // 获取键
            for (let k in json[0]) {keyMap.push(k);
            }
            console.info('keyMap', keyMap, json);
            let tmpdata = []; // 用来保留转换好的 json
            json.map((v, i) =>
                keyMap.map((k, j) =>
                    Object.assign({},
                        {v: v[k],
                            position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
                        }
                    )
                )
            )
                .reduce((prev, next) => prev.concat(next))
                .forEach(function(v) {tmpdata[v.position] = {v: v.v};
                });
            let outputPos = Object.keys(tmpdata); // 设置区域, 比方表格从 A1 到 D10
            let tmpWB = {SheetNames: ['mySheet'], // 保留的表题目
                Sheets: {
                    mySheet: Object.assign({},
                        tmpdata, // 内容
                        {'!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
                        }
                    )
                }
            };
            let tmpDown = new Blob(
                [
                    this.s2ab(
                        XLSX.write(
                            tmpWB,
                            {bookType: type === undefined ? 'xlsx' : type, bookSST: false, type: 'binary'} // 这里的数据是用来定义导出的格局类型
                        )
                    )
                ],
                {type: ''}
            ); // 创立二进制对象写入转换好的字节流
            var href = URL.createObjectURL(tmpDown); // 创建对象超链接
            this.outFile.download = downName + '.xlsx'; // 下载名称
            this.outFile.href = href; // 绑定 a 标签
            this.outFile.click(); // 模仿点击实现下载
            setTimeout(function() {
                // 延时开释
                URL.revokeObjectURL(tmpDown); // 用 URL.revokeObjectURL() 来开释这个 object URL}, 100);
        },
        
        s2ab: function(s) {
            // 字符串转字符流
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i !== s.length; ++i) {view[i] = s.charCodeAt(i) & 0xff;
            }
            return buf;
        },
        getCharCol: function(n) {// 将指定的自然数转换为 26 进制示意。映射关系:[0-25] -> [A-Z]。let s = '';
            let m = 0;
            while (n > 0) {m = (n % 26) + 1;
                s = String.fromCharCode(m + 64) + s;
                n = (n - m) / 26;
            }
            return s;
        }
    }
};
</script>

<style scoped>
.excel-upload-input {
    display: none;
    z-index: -9999;
}
.drop {
    border: 2px dashed #bbb;
    width: 600px;
    height: 160px;
    line-height: 160px;
    margin: 0 auto;
    font-size: 24px;
    border-radius: 5px;
    text-align: center;
    color: #bbb;
    position: relative;
}
</style>
3. 应用组件
<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

export default {
  name: 'UploadExcel',
  components: {UploadExcelComponent},
  data() {
    return {tableData: [],
      tableHeader: []}
  },
  methods: {beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {return true}

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({results, header}) {
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>

正文完
 0