vue实现表格的导入和导出

作者: it之承影含光 | 来源:发表于2017-08-30 16:43 被阅读1632次

    1.表格的导入

    引用js-xlsx
    官方示例:http://oss.sheetjs.com/js-xlsx/

    代码的实现

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    
    <body>
        <div id="app" v-cloak>
            <input type="file" @change="importExcel($event.target)" />
            <div style="overflow: auto;" v-if="tableTbody&&tableTbody.length>0">
                <table class="table table-bordered" style="min-width: 100%;">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th v-for="(item,index) in tableHeader" :key="index">
                                {{item}}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(row,index) in tableTbody" :key="index">
                            <th scope="row">{{index}}</th>
                            <td v-for="col in tableHeader">{{row[col]}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </body>
    <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdn.bootcss.com/xlsx/0.11.3/xlsx.full.min.js"></script>
    <script>
        var app = new Vue({
            el: "#app",
            data() {
                return {
                    wb: '',
                    tableHeader: [],
                    tableTbody: []
                }
            },
            methods: {
                importExcel(obj) {
                    if (!obj.files) {
                        return;
                    }
                    let file = obj.files[0],
                        types = file.name.split('.')[1],
                        fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(item => item === types);
                    if (!fileType) {
                        alert("格式错误!请重新选择");
                        return;
                    }
                    this.file2Xce(file).then(tabJson => {
                        if (tabJson && tabJson.length > 0) {
                            this.tableHeader = Object.keys(tabJson[0]);
                            this.tableTbody = tabJson;
                        }
                    });
                },
                file2Xce(file) {
                    return new Promise(function (resolve, reject) {
                        let reader = new FileReader();
                        reader.onload = function (e) {
                            let data = e.target.result;
                            this.wb = XLSX.read(data, {
                                type: 'binary'
                            });
                            resolve(XLSX.utils.sheet_to_json(this.wb.Sheets[this.wb.SheetNames[0]]));
                        };
                        reader.readAsBinaryString(file);
                    });
                }
            }
        })
    </script>
    
    </html>
    

    2.表格的导出

    这里是使用js-xlsx的table_to_book方法实现,还有另一种是拼接excel格式的具体请参考纯前端利用 js-xlsx 实现 Excel 文件导入导出功能示例

    代码的实现

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    
    <body>
        <div id="app" v-cloak>
            <button @click="downloadExl">导出</button>
            <div id="tableId">
                <table class="table table-bordered" style="min-width: 100%;">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th v-for="(item,index) in Object.keys(jsonData[0])" :key="index">
                                {{item}}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(row,index) in jsonData" :key="index">
                            <th scope="row">{{index}}</th>
                            <td v-for="col in Object.keys(jsonData[0])">{{(row)[col]}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </body>
    <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
    <script src="https://cdn.bootcss.com/xlsx/0.11.3/xlsx.full.min.js"></script>
    <script>
        var app = new Vue({
            el: "#app",
            data() {
                return {
                    jsonData: [{
                        "订单id": "574",
                        "订单时间": "2017-06-30 13:09:59",
                        "下单店铺名称": "金湖世纪华联(测试)",
                        "店铺联系人": "小杨",
                        "联系电话": "021-33829544",
                        "配送地址": "浦东新区金桥镇五莲路1706号",
                        "一级分类": "个人洗护",
                        "二级分类": "洗手液/身体乳",
                        "商品名称": "百雀羚护手霜 18.5g/个",
                        "供应商名称": "新增供应商123",
                        "订购数量": "6",
                        "商品单价": "23.00",
                        "商品箱规": "2.00",
                        "合计x箱": "3.00"
                    }]
                }
            },
            methods: {
                downloadExl() {
                    let wb = XLSX.utils.table_to_book(document.getElementById('tableId')),
                        wopts = {
                            bookType: 'xlsx',
                            bookSST: false,
                            type: 'binary'
                        },
                        wbout = XLSX.write(wb, wopts);
    
                    saveAs(new Blob([this.s2ab(wbout)], {
                        type: "application/octet-stream;charset=utf-8"
                    }), "test.xlsx");
                },
                s2ab(s) {
                    if (typeof ArrayBuffer !== 'undefind') {
                        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;
                    } else {
                        var buf = new Array(s.length);
                        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
                        return buf;
                    }
                }
            }
        })
    </script>
    
    </html>
    

    参考资料

    纯前端利用 js-xlsx 实现 Excel 文件导入导出功能示例
    Vue2 导出excel
    在 Node.js 中利用 js-xlsx 处理 Excel 文件

    相关文章

      网友评论

      本文标题:vue实现表格的导入和导出

      本文链接:https://www.haomeiwen.com/subject/hewuqxtx.html