JS直接将页面的内容作为excel下载

  做个笔记,后续自己可以看看,将页面的一个Table直接输出为excel文件,亲测有用。

 

 //下载excel
        function downloadExcel() {
            var uri = 'data:application/vnd.ms-excel;base64,';
            var 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">
                    <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
                    <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                    <x:Name>sheet1</x:Name>
                    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                    </head><body><table>`+ $('#idData').html() + `</table></body></html>`;
            window.location.href = uri + window.btoa(unescape(encodeURIComponent(template)));
        };

  

function download2() {
            var uri = 'data:application/vnd.ms-excel;base64,';
            var 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">
                   <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
                   <meta http-equiv="content-disposition" content="attachment;filename=123.xlsx">
                   <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                   <x:Name>sheet1</x:Name>
                   <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                   </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                   </head><body>`+ $('#rptData').html() + `</body></html>`;

            
            var a = document.createElement('a')
            a.download = "123.xls";
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            document.body.appendChild(a)
            a.click();
            document.body.removeChild(a)
        }

  

posted @ 2023-07-28 10:05  老飞飞  阅读(242)  评论(1)    收藏  举报