• html 前端数据导出excel


    1、前端数据

        ①、初始化数据

    1 var data = [
    2                 { id: 12, name: "张三", age: 12 }, { id: 13, name: "李四", age: 13 }, { id: 14, name: "王五", age: 14 },
    3                 { id: 15, name: "赵六", age: 15 }
    4             ];

    2、构建表格样式

       ①、表结构

       

     1 var table = '<table border="1px" cellspacing="0" cellpadding="0">';
     2             table += '<thead>';
     3             table += '<th>日期</th>';
     4             table += '<th>name</th>';
     5             table += '<th>age</th>';
     6             table += '<th>sex</th>';
     7             table += '</thead>';
     8             table += '<tbody>';
     9 
    10            
    11             var _body = "";
    12             for (var row = 0; row < data.length; row++) {
    13                 _body += '<tr>';
    14                 _body += '<td>';
    15                 _body += `${data[row].id}`;
    16                 _body += '</td>';
    17                 _body += '<td>';
    18                 _body += `${data[row].name}`;
    19                 _body += '</td>';
    20                 _body += '<td>';
    21                 _body += `${data[row].age}`;
    22                 _body += '</td>';
    23                 _body += '</tr>';
    24             }
    25             table += _body;
    26             table += '</tbody>';
    27             table += '</table>';
    28             excel(table, "excel.xlsx");

    3、导出表格

      ①、编写导出表格方法

    function excel(data, filename) {
                var html =
                    "<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'>";
                html += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
                html += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
                html += '; charset=UTF-8">';
                html += "<head>";
                html += "</head>";
                html += "<body>";
                html += data;
                html += "</body>";
                html += "</html>";
                var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
                var link = document.createElement("a");
                link.href = uri;
                link.style = "visibility:hidden";
                link.download = `${filename}`; 
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
  • 相关阅读:
    Gym 101194L / UVALive 7908
    POJ 2259
    POJ 2559
    Gym 101194E / UVALive 7901
    Gym 101194D / UVALive 7900
    一种整数集上二分的正确写法
    日常训练记录
    Gym 101194C / UVALive 7899
    Gym 101194A / UVALive 7897
    HDU 5542
  • 原文地址:https://www.cnblogs.com/study10000/p/12073733.html
Copyright © 2020-2023  润新知