Several ways to export Excel from table table in Vue project

Several ways to export Excel from table table in Vue project

The first

This method requires the installation of plugins FileSaver and XLSX

JS
Export(){  //导出Excel
             let et = XLSX.utils.table_to_book(
                document.getElementById("Table1")
            ); //此处传入table的DOM节点
            let etout = XLSX.write(et, {
                bookType: "xlsx",
                bookSST: true,
                type: "array"
            });
            try {
                FileSaver.saveAs(
                    new Blob([etout], {
                        type: "application/octet-stream"
                    }),
                    "XX清单.xlsx"
                ); //trade-publish.xlsx 为导出的文件名
            } catch (e) {
                console.log(e, etout);
            }
            return etout;
        },

the second

This method needs to get the data first, and then write out the fields that need to be exported. This method is relatively simple, but cannot be shared. If there are many places to export, you need to write multiple times.

let th = [
                            "序号",
                            "名称",
                            "所需时间",
                            "状态",
                            "数量",
                        ];
                        let value = [
                            1,
                            "Name",
                            "Time"
                            "State",
                            "Amount",
                        ];
                        // 拿到要导出的数据
                        let data = this.listsAll.map((v) =>
                            value.map((k) => v[k])
                        );
                        data.forEach((el, index) => {
                        //对表格数据内容修改
                            el[0] = index + 1;
                            el[3] = this.$options.filters["State"](el[3]);
                        });
                        const [fileName, fileType, sheetName] = [
                            "XX清单",
                            "xlsx",
                            "XX清单",
                        ];
                        this.$toExcel({
                            th,
                            data,
                            fileName,
                            fileType,
                            sheetName,
                        });

third

This method only needs to define the id and name of the table, which can be used directly and can be written as a public method. But sometimes the numbers in the table are longer, this method will change the words in the table into scientific notation by default.

Export(id, name) {
            //获取表格
            var exportFileContent = document.getElementById("" + id + "")
                .outerHTML;
            //设置格式为Excel,表格内容通过btoa转化为base64,此方法只在文件较小时使用(小于1M)
            //exportFileContent=window.btoa(unescape(encodeURIComponent(exportFileContent)));
            //var link = "data:"+MIMEType+";base64," + exportFileContent;
            //使用Blob
            console.log("blob:", exportFileContent);
            var blob = new Blob([exportFileContent], {
                type: "text/plain;charset=utf-8",
            }); //解决中文乱码问题

            blob = new Blob([String.fromCharCode(0xfeff), blob], {
                type: blob.type,
            });

            //设置链接

            var link = window.URL.createObjectURL(blob);

            var a = document.createElement("a"); //创建a标签

            a.download = name + ".xls"; //设置被下载的超链接目标(文件名)

            a.href = link; //设置a标签的链接

            document.body.appendChild(a); //a标签添加到页面

            a.click(); //设置a标签触发单击事件

            document.body.removeChild(a); //移除a标签

fourth

Because with the third method, the exported data once became scientific notation in excel, so this method solves the problem of numbers becoming scientific notation, and converts all data into text form.

Export(id,name){
		var uri = "data:application/vnd.ms-excel;base64,",
                    template =
                        '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)));
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g, function (m, p) {
                            return c[p];
                        });
                    };

                var table = document.getElementById("tables");

                //console打印出table.innerHTML出则是table的页面代码
                //根据正则表达式,把style='mso-number-format:"\@"' 塞入td中,将数据转成String
                table.innerHTML = table.innerHTML.replace(
                    /<td/g,
                    "<td STYLE='MSO-NUMBER-FORMAT:\\@'"
                );

                var ctx = {
                    worksheet: name || "Worksheet",
                    table: table.innerHTML,
                }; //此时的innerHTML数据可以自己自定义 比如json转化 只要值要数据符合即可
                var link = document.createElement("A");
                link.href = uri + base64(format(template, ctx));
                link.download = name + ".xls";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
}

These are the only methods I use so far, feel free to add more!

Guess you like

Origin blog.csdn.net/weixin_49609457/article/details/119252015