Vue pure front-end table export excel

When developing the front-end, you need to export tabular data. Here is a pure front-end export to excel, without back-end interface support.

Features of the code:

  1. What you see is what you get, what the front end displays, and what the content of the exported table is.
  2. Support multiple workbooks, you can export multiple data of the same page at one time.
  3. Disadvantages: If the data has back-end paging, please don't use it.
<script>
import FileSaver from "file-saver"
import XLSX from "xlsx"

exportExcel() {
            /*获取表格数据 */
            var wb = XLSX.utils.book_new()
            var centers = XLSX.utils.table_to_sheet(document.querySelector("#center_table"))
            var products = XLSX.utils.table_to_sheet(document.querySelector("#product_table"))
            var center_month = XLSX.utils.table_to_sheet(document.querySelector("#center_table_month"))
            var departs = XLSX.utils.table_to_sheet(document.querySelector("#depart_table"))

            /* 添加多个工作薄,如果只有一个,则只写一个 */
            XLSX.utils.book_append_sheet(wb, center_month, "各中心月度费用统计")
            XLSX.utils.book_append_sheet(wb, centers, "各中心申请费用类型统计")
            XLSX.utils.book_append_sheet(wb, products, "各业务产品申请费用统计")
            XLSX.utils.book_append_sheet(wb, departs, "各部门申请费用统计")

            var wbout = XLSX.write(wb, {
                bookType: "xlsx",
                bookSST: true,
                type: "array"
            })
            try {
                FileSaver.saveAs(
                    // Blob 对象表示一个不可变、原始数据的类文件对象。
                    // Blob 表示的不一定是JavaScript原生格式的数据。
                    // File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
                    // 返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
                    new Blob([wbout], { type: "application/octet-stream" }),
                    // 设置导出文件名称 xxx.xlsx
                    "中心申请费用类型统计.xlsx"
                )
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, wbout)
            }
            return wbout
        },

</script>

Guess you like

Origin blog.51cto.com/yangrong/2542955