前端表格导出

94 阅读1分钟

js-xlsx 前端表格导出

页面

image.png

导出效果

image.png

代码

插件生成的表格因为兼容一些功能,最终渲染的时候其实是多个table元素,为了能将表格完整的导出(thead+body),需要手动拼接dom

onExport() {
            // 创建新的table元素
            var print_table_dom = document.createElement('table')
            // copy一份thead
            var print_table_dom_thead = document.querySelector('table thead').cloneNode(true)
            // copy一份tbody
            var print_table_dom_body = document.querySelector('table tbody').cloneNode(true)
            print_table_dom.appendChild(print_table_dom_thead)
            print_table_dom.appendChild(print_table_dom_body)

            //将dom转换为book
            const new_book = XLSX.utils.table_to_book(print_table_dom)

            // 导出excel文件 如导出后的文件不能打开,请将后缀替换为 .xls
            XLSX.writeFile(new_book, '数据导出.xlsx')
        }