前端数据表格excel导出代码

 

 

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
</head>

<body>
    <p style="font-size: 20px;">json格式导出excel文件</p>
    <button onclick='tableToExcel()'>导出</button>
    <script>
        function tableToExcel() {
            //要导出的json数据
            const jsonData = [{
                    name: '张三',
                    phone: '123456',
                    email: '123@123456.com'
                }, {
                    name: '李四',
                    phone: '123456',
                    email: '123@123456.com'
                }, {
                    name: '王五',
                    phone: '123456',
                    email: '123@123456.com'
                }, {
                    name: '老六',
                    phone: '123456',
                    email: '123@123456.com'
                }, ]
                //列标题
            let head = `<tr><th>表头1</th><th>表头2</th><th>表头3</th></tr>`;
            let tbody = ""; //内容
            for (let item in jsonData) {
                tbody +=
                    `<tr>
                        <td>${jsonData[item].name + '\t'}</td>
                        <td>${jsonData[item].phone + '\t'}</td>
                        <td>${jsonData[item].email + '\t'}</td>
                    </tr>`
            }
            let str = head + tbody; //头部跟身体内容连接


            //Worksheet名
            let worksheet = 'Sheet1'
            let uri = 'data:application/vnd.ms-excel;base64,';

            //下载的表格模板数据
            let 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><!--[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 border="1">${str}</table></body></html>`;
            //下载模板
            console.log(str)
            window.location.href = uri + base64(template)
        }
        //输出base64编码
        function base64(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        }
    </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值