html table表格導出excel的方法 html5 table導出Excel HTML用JS導出Excel的五種方法 html中table導出Excel 前端開發 將table內容...

先上代碼javascript

 

  1.  
    <script type= "text/javascript" language="javascript">
  2.  
    var idTmr;
  3.  
     
  4.  
    function getExplorer() {
  5.  
    var explorer = window.navigator.userAgent;
  6.  
    //ie
  7.  
    if (explorer.indexOf("MSIE") >= 0) {
  8.  
    return 'ie';
  9.  
    }
  10.  
    //firefox
  11.  
    else if (explorer.indexOf("Firefox") >= 0) {
  12.  
    return 'Firefox';
  13.  
    }
  14.  
    //Chrome
  15.  
    else if (explorer.indexOf("Chrome") >= 0) {
  16.  
    return 'Chrome';
  17.  
    }
  18.  
    //Opera
  19.  
    else if (explorer.indexOf("Opera") >= 0) {
  20.  
    return 'Opera';
  21.  
    }
  22.  
    //Safari
  23.  
    else if (explorer.indexOf("Safari") >= 0) {
  24.  
    return 'Safari';
  25.  
    }
  26.  
    }
  27.  
     
  28.  
    function method1(tableid,name="1.xlsx") { //整個表格拷貝到EXCEL中
  29.  
    if (getExplorer() == 'ie') {
  30.  
    var curTbl = document.getElementById(tableid);
  31.  
    var oXL = new ActiveXObject("Excel.Application");
  32.  
     
  33.  
    //建立AX對象excel
  34.  
    var oWB = oXL.Workbooks.Add();
  35.  
    //獲取workbook對象
  36.  
    var xlsheet = oWB.Worksheets(1);
  37.  
    //激活當前sheet
  38.  
    var sel = document.body.createTextRange();
  39.  
    sel.moveToElementText(curTbl);
  40.  
    //把表格中的內容移到TextRange中
  41.  
    sel.select;
  42.  
    //全選TextRange中內容
  43.  
    sel.execCommand( "Copy");
  44.  
    //複製TextRange中內容
  45.  
    xlsheet.Paste();
  46.  
    //粘貼到活動的EXCEL中
  47.  
    oXL.Visible = true;
  48.  
    //設置excel可見屬性
  49.  
     
  50.  
    try {
  51.  
    var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  52.  
    } catch (e) {
  53.  
    print( "Nested catch caught " + e);
  54.  
    } finally {
  55.  
    oWB.SaveAs(fname);
  56.  
     
  57.  
    oWB.Close(savechanges = false);
  58.  
    //xls.visible = false;
  59.  
    oXL.Quit();
  60.  
    oXL = null;
  61.  
    //結束excel進程,退出完成
  62.  
    //window.setInterval("Cleanup();",1);
  63.  
    idTmr = window.setInterval("Cleanup();", 1);
  64.  
     
  65.  
    }
  66.  
     
  67.  
    } else {
  68.  
    tableToExcel(tableid,name)
  69.  
    }
  70.  
    }
  71.  
     
  72.  
    function Cleanup() {
  73.  
    window.clearInterval(idTmr);
  74.  
    CollectGarbage();
  75.  
    }
  76.  
    var tableToExcel = (function () {
  77.  
    var uri = 'data:application/vnd.ms-excel;base64,',
  78.  
    template =
  79.  
    '<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>{table}</table></body></html>',
  80.  
    base64 = function (s) {
  81.  
    return window.btoa(unescape(encodeURIComponent(s)))
  82.  
    },
  83.  
    format = function (s, c) {
  84.  
    return s.replace(/{(\w+)}/g,
  85.  
    function (m, p) {
  86.  
    return c[p];
  87.  
    })
  88.  
    }
  89.  
    return function (table, name) {
  90.  
    console.log(table,name)
  91.  
    if (!table.nodeType) table = document.getElementById(table)
  92.  
    var ctx = {
  93.  
    worksheet: name || 'Worksheet',
  94.  
    table: table.innerHTML
  95.  
    }
  96.  
    return;
  97.  
    window.location.href = uri + base64(format(template, ctx))
  98.  
    }
  99.  
    })();
  100.  
    </script>

 

  1.  
    $( '#export').click(function () {
  2.  
    method1( 'table');
  3.  
    })
$('#export').attr('href',uri + base64(format(template, ctx))) //解決文件無擴展名的問題




 

 

轉載自http://blog.csdn.net/sinat_15114467/article/details/51098522php

github也有寫好的插件:css

 

  1.  
    jQuery table2excel - v1 .1.1
  2.  
    * jQuery plugin to export an .xls file in browser from an HTML table
  3.  
    * https: //github.com/rainabba/jquery-table2excel



 

 

這個地址也是相關的介紹https://segmentfault.com/a/1190000000336643html

個人html實例html5

 

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="gb2312">
  5.  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.  
    <title>數據</title>
  7.  
    <style>
  8.  
    * {
  9.  
    margin: 0;
  10.  
    padding: 0;
  11.  
    text-decoration: none;
  12.  
    list-style: none;
  13.  
    font-size: 20px;
  14.  
    }
  15.  
    body{
  16.  
    text-align: center;
  17.  
    }
  18.  
    .agent{
  19.  
    text-align: left;
  20.  
    }
  21.  
    table {
  22.  
    width: 1200px;
  23.  
    margin: 0 auto;
  24.  
    vertical-align: center;
  25.  
    font-size: 18px;
  26.  
    text-align: center;
  27.  
    border: 1px solid #ccc;
  28.  
    }
  29.  
     
  30.  
    td,
  31.  
    th {
  32.  
    border: 1px solid #000;
  33.  
    overflow: hidden;
  34.  
    }
  35.  
     
  36.  
    .kefu {
  37.  
    width: 70px;
  38.  
    }
  39.  
     
  40.  
    .page {
  41.  
    text-align: center;
  42.  
    font-size: 20px;
  43.  
    }
  44.  
     
  45.  
    .page a {
  46.  
    display: inline-block;
  47.  
    }
  48.  
     
  49.  
    #export {
  50.  
    display: block;
  51.  
    text-align: center;
  52.  
    font-size: 20px;
  53.  
    }
  54.  
    /* 時間和日期 */
  55.  
     
  56.  
    #choose {
  57.  
    width: 1200px;
  58.  
    margin: 20px auto;
  59.  
    text-align: center;
  60.  
    }
  61.  
    /* 對話框 */
  62.  
     
  63.  
    .convBox {
  64.  
    position: fixed;
  65.  
    top: 0px;
  66.  
    left: 0;
  67.  
    bottom: 0;
  68.  
    right: 0;
  69.  
    margin: auto;
  70.  
    width: 1200px;
  71.  
    height: 500px;
  72.  
    overflow: auto;
  73.  
    display: none;
  74.  
    background: #ccc;
  75.  
    border: 1px solid #000;
  76.  
    }
  77.  
     
  78.  
    .convBox h6 {
  79.  
    font-size: 20px;
  80.  
    margin: 15px 0;
  81.  
    text-align: center;
  82.  
    }
  83.  
     
  84.  
    .convBox .close {
  85.  
    position: absolute;
  86.  
    top: 8px;
  87.  
    right: 8px;
  88.  
    font-size: 20px;
  89.  
    }
  90.  
     
  91.  
    .convBox li {
  92.  
    float: left;
  93.  
    margin: 8px 20px;
  94.  
    }
  95.  
     
  96.  
    .clearfix:after {
  97.  
    content: '';
  98.  
    display: block;
  99.  
    height: 0;
  100.  
    visibility: hidden;
  101.  
    clear: both;
  102.  
    }
  103.  
     
  104.  
    .clearfix {
  105.  
    zoom: 1;
  106.  
    }
  107.  
     
  108.  
    .mainCon .agent,
  109.  
    .mainCon .client {
  110.  
    padding: 8px 20px;
  111.  
    }
  112.  
     
  113.  
    .mainCon .client {
  114.  
    text-align: right;
  115.  
    background: #68c558;
  116.  
    }
  117.  
    </style>
  118.  
    </head>
  119.  
    <body>
  120.  
    <div id="choose">
  121.  
    <input type="text" class="startTm">
  122.  
    <input type="text" class="endTm">
  123.  
    <button>提交</button>
  124.  
    </div>
  125.  
    <table id="table">
  126.  
    <tr>
  127.  
    <th>編號</th>
  128.  
    <th>對話開始時間</th>
  129.  
    <th>會話結束時間</th>
  130.  
    <th>客戶id</th>
  131.  
    <th>搜索關鍵詞</th>
  132.  
    <th class="kefu">客服</th>
  133.  
    <th>客服首次響應訪客的等待時</th>
  134.  
    <th>訪客的消息數</th>
  135.  
    <th>對話內容</th>
  136.  
    <th>客戶地點</th>
  137.  
    <th>IP</th>
  138.  
    </tr>
  139.  
    </table>
  140.  
    <p class="page">
  141.  
    <a href="javascript:void(0)" class="prev">上一頁</a>
  142.  
    <a href="javascript:void(0)" class="next">下一頁</a>
  143.  
    <span></span>
  144.  
    </p>
  145.  
    <a href="javascript:void(0)" id="export" download="對話記錄.xlsx">導出對話記錄</a>
  146.  
    <div class="convBox">
  147.  
    <h6><span></span>的對話</h6>
  148.  
    <a href="javascript:void(0)" class="close">X</a>
  149.  
    <ul class="contentKey clearfix">
  150.  
    <li class="agent_name">
  151.  
    客服: <span>dfsdfsfs</span>
  152.  
    </li>
  153.  
    <li class="wait_in_secs">
  154.  
    對話等待時間: <span>5</span>S
  155.  
    </li>
  156.  
    <li class="visitor_ip">
  157.  
    IP: <span>yan</span>
  158.  
    </li>
  159.  
    <li class="visitor_location">
  160.  
    地點: <span>yan</span>
  161.  
    </li>
  162.  
    <li class="search_engine_kw">
  163.  
    搜索關鍵詞: <span>sdfsfsfsdfsfsfsgsdsg</span>
  164.  
    </li>
  165.  
    <li class="conv_start_tm">
  166.  
    對話開始時間: <span>sdfsfsfsdfsfsfsgsdsg</span>
  167.  
    </li>
  168.  
    <li class="conv_end_tm">
  169.  
    對話結束時間: <span>sdfsfsfsdfsfsfsgsdsg</span>
  170.  
    </li>
  171.  
    </ul>
  172.  
    <div class="mainCon clearfix">
  173.  
     
  174.  
    </div>
  175.  
    </div>
  176.  
    <script src="js/jquery-1.11.3.min.js"></script>
  177.  
    <script>
  178.  
    var tableList= '<tr>\
  179.  
    <th>編號</th>\
  180.  
    <th>對話開始時間</th>\
  181.  
    <th>會話結束時間</th>\
  182.  
    <th>客戶id</th>\
  183.  
    <th>搜索關鍵詞</th>\
  184.  
    <th class="kefu">客服</th>\
  185.  
    <th>客服首次響應訪客的等待時</th>\
  186.  
    <th>訪客的消息數</th>\
  187.  
    <th>對話內容</th>\
  188.  
    <th>客戶地點</th>\
  189.  
    <th>IP</th>\
  190.  
    </tr>';
  191.  
    $( document).ready(function () {
  192.  
    var pageAll='';//計算總數時用的參數
  193.  
    var pagesize = 0; //顯示頁
  194.  
    var limit = 20; //每頁顯示的數目
  195.  
    var offset = pagesize * limit; //跳過的數目
  196.  
    var startTm = $('.startTm').val();
  197.  
    var endTm = $('.endTm').val();
  198.  
    //初始化時間
  199.  
    var startTm = getFormatDate('ymd');
  200.  
    var endTm = getFormatDate('ymd');
  201.  
    $( '.startTm').val(getFormatDate('ymd'));
  202.  
    $( '.endTm').val(getFormatDate('ymd'));
  203.  
     
  204.  
    var data1 = {
  205.  
    startTm: startTm,
  206.  
    endTm: endTm,
  207.  
    offset: 0
  208.  
    };
  209.  
    //ajax請求
  210.  
    function ajax(data1) {
  211.  
    // console.log(data1)
  212.  
    $.ajax({
  213.  
    url: "php/index.php",
  214.  
    data: data1,
  215.  
    success: function (data) {
  216.  
    console.log(data)
  217.  
    var newJson = JSON.parse(data);
  218.  
    if (newJson.result.length < 20) {
  219.  
    $( '.page span').text("已是最後一頁");
  220.  
    } else if (newJson.result.length <= 0) {
  221.  
    $( '.page span').text("已是最後一頁");
  222.  
    return;
  223.  
    } else {
  224.  
    var Nowpage = pagesize + 1;
  225.  
    $( '.page span').text("當前是第" + Nowpage + "頁");
  226.  
    }
  227.  
    // addContent(newJson.result)
  228.  
    tableList+=addContent(newJson.result);
  229.  
    $( '#table').append(addContent(newJson.result));
  230.  
    }
  231.  
    })
  232.  
    }
  233.  
    function ajax2(data1) {
  234.  
    $.ajax({
  235.  
    url: "php/index.php",
  236.  
    data: data1,
  237.  
    success: function (data) {
  238.  
    var newJson = JSON.parse(data);
  239.  
    tableList+=addContent(newJson.result);
  240.  
    if (newJson.result.length < 20 || newJson.result.length <= 0) {
  241.  
    // console.log(tableList)
  242.  
    var dateN=(new Date()).toLocaleString();
  243.  
    // console.log(dateN)
  244.  
    // return;
  245.  
    method1(tableList,dateN);
  246.  
    // return tableList;
  247.  
    } else {
  248.  
    allrecord();
  249.  
    }
  250.  
    }
  251.  
    })
  252.  
    }
  253.  
    //調出全部的記錄
  254.  
    function allrecord(){
  255.  
    pageAll++;
  256.  
    var offset = pageAll * limit; //跳過的數目
  257.  
    var startTm = $('.startTm').val();
  258.  
    var endTm = $('.endTm').val();
  259.  
    var data1 = {
  260.  
    startTm: startTm,
  261.  
    endTm: endTm,
  262.  
    offset: offset
  263.  
    }
  264.  
    ajax2(data1);
  265.  
    }
  266.  
    ajax(data1);
  267.  
    //插入對話內容
  268.  
    function addContent(rs) {
  269.  
    // console.log(rs)
  270.  
    var arr = [];
  271.  
    var length = rs.length;
  272.  
    for (var i = 0; i < length; i++) {
  273.  
    if(!rs[i]){continue;}
  274.  
    arr.push( '<tr>');
  275.  
    arr.push( '<td>' + i + '</td>');
  276.  
    arr.push( '<td>' + rs[i].conv_start_tm + '</td>');
  277.  
    arr.push( '<td>' + rs[i].conv_end_tm + '</td>');
  278.  
    arr.push( '<td>' + rs[i].client_info.visitor_name + '</td>');
  279.  
    arr.push( '<td>' + rs[i].search_engine_kw + '</td>');
  280.  
    arr.push( '<td>' + rs[i].agent_name + '</td>');
  281.  
    arr.push( '<td>' + rs[i].wait_in_secs + '</td>');
  282.  
    arr.push( '<td>' + rs[i].conv_visitor_msg_count + '</td>');
  283.  
    if(rs[i].conv_visitor_msg_count>0){
  284.  
    let con = '';
  285.  
    let conLen = rs[i].conv_content.length;
  286.  
    for(let j=0;j<conLen;j++){
  287.  
    con+=rs[i].conv_content[j].from+rs[i].conv_content[j].timestamp+rs[i].conv_content[j].content;
  288.  
    }
  289.  
    arr.push( '<td class="convId">' + con + '<span>' + rs[i].conv_id + '</span></td>');
  290.  
    } else{
  291.  
    arr.push( '<td class="convId">' + '點擊顯示內容<span>' + rs[i].conv_id + '</span></td>');
  292.  
    }
  293.  
    arr.push( '<td>' + rs[i].visitor_location + '</td>');
  294.  
    arr.push( '<td>'+rs[i].visitor_ip+'</td>');
  295.  
    arr.push( '</tr>');
  296.  
    }
  297.  
    // tableList+=arr.join('')
  298.  
    // $('#table').append(arr.join(''));
  299.  
    return arr.join('');
  300.  
    }
  301.  
    $( '.prev').click(function () {
  302.  
    $( "#table tr").not($("#table tr:first")).remove();
  303.  
    pagesize = (--pagesize < 0) ? 0 : pagesize;
  304.  
    offset = pagesize * limit; //跳過的數目
  305.  
    startTm = $( '.startTm').val();
  306.  
    endTm = $( '.endTm').val();
  307.  
    var data1 = {
  308.  
    startTm: startTm,
  309.  
    endTm: endTm,
  310.  
    offset: offset
  311.  
    }
  312.  
    ajax(data1);
  313.  
    })
  314.  
    $( '.next').click(function () {
  315.  
    $( "#table tr").not($("#table tr:first")).remove();
  316.  
    if ($('.page span').text() == '已是最後一頁') {
  317.  
    return false;
  318.  
    }
  319.  
    pagesize = (++pagesize < 0) ? 0 : pagesize;
  320.  
    // console.log(pagesize)
  321.  
    var offset = pagesize * limit; //跳過的數目
  322.  
    var startTm = $('.startTm').val();
  323.  
    var endTm = $('.endTm').val();
  324.  
    var data1 = {
  325.  
    startTm: startTm,
  326.  
    endTm: endTm,
  327.  
    offset: offset
  328.  
    }
  329.  
    ajax(data1);
  330.  
    })
  331.  
    // 日期選擇表單
  332.  
    $( '#choose button').click(function () {
  333.  
    pagesize= 0;
  334.  
    var startTm = $('.startTm').val();
  335.  
    var endTm = $('.endTm').val();
  336.  
    var data1 = {
  337.  
    startTm: startTm,
  338.  
    endTm: endTm,
  339.  
    offset: 0
  340.  
    }
  341.  
    $( "#table tr").not($("#table tr:first")).remove();
  342.  
    ajax(data1);
  343.  
    });
  344.  
    // 當前時間的函數
  345.  
    /*
  346.  
    * @param param string 肯定時間的顯示格式 'ymd' => 年-月-日
  347.  
    * 其它 => 年-月-日+時:分:秒
  348.  
    * @param num num +1表明後一天,-1表明前一天
  349.  
    *
  350.  
    **/
  351.  
    function getFormatDate(param, num = 0) {
  352.  
    var date = new Date();
  353.  
    var seperator1 = "-";
  354.  
    var seperator2 = ":";
  355.  
    var seperator3 = '+';
  356.  
    var y = date.getFullYear();
  357.  
    var m = date.getMonth() + 1;
  358.  
    var d = date.getDate() + num;
  359.  
    var h = date.getHours();
  360.  
    var i = date.getMinutes();
  361.  
    var s = date.getSeconds();
  362.  
    if (m >= 1 && m <= 9) {
  363.  
    m = "0" + m;
  364.  
    }
  365.  
    d = d <= 0 ? 1 : d;
  366.  
    if (d >= 0 && d <= 9) {
  367.  
    d = "0" + d;
  368.  
    }
  369.  
    if (param = 'ymd') {
  370.  
    var currentdate = y + seperator1 + m + seperator1 + d;
  371.  
    } else {
  372.  
    var currentdate = y + seperator1 + m + seperator1 + d +
  373.  
    seperator3 + h + seperator2 + i +
  374.  
    seperator2 + s;
  375.  
    }
  376.  
    return currentdate;
  377.  
    }
  378.  
    // 顯示聊天內容
  379.  
    $( document).on('click', '.convId', function () {
  380.  
    var convId = $(this).find('span').text();
  381.  
    var data1 = {
  382.  
    conv_id: convId
  383.  
    }
  384.  
    $.ajax({
  385.  
    url: "php/conv.php",
  386.  
    data: data1,
  387.  
    success: function (data) {
  388.  
    var newJson = (new Function("", "return " + data))(data).result;
  389.  
    // console.log(newJson)
  390.  
    $( '.convBox h6 span').text(convId);
  391.  
    $( '.convBox .agent_name span').text(newJson.agent_name);
  392.  
    $( '.convBox .wait_in_secs span').text(newJson.wait_in_secs);
  393.  
    $( '.convBox .visitor_ip span').text(newJson.visitor_ip);
  394.  
    $( '.convBox .visitor_location span').text(newJson.visitor_location);
  395.  
    $( '.convBox .search_engine_kw span').text(newJson.search_engine_kw);
  396.  
    $( '.convBox .conv_end_tm span').text(newJson.conv_end_tm);
  397.  
    $( '.convBox .conv_start_tm span').text(newJson.conv_start_tm);
  398.  
    $( '.convBox .visitor_location span').text(newJson.visitor_location);
  399.  
    let convLen = newJson.conv_content.length;
  400.  
    let conv_content = [];
  401.  
    // console.log(convLen)
  402.  
    for (let j = 0; j < convLen; j++) {
  403.  
    // conv_content.push(111)
  404.  
    conv_content.push( '<div class="' + newJson.conv_content[j].from +
  405.  
    '"><p>' + newJson.conv_content[j].timestamp + '</p>' +
  406.  
    newJson.conv_content[j].content + '</div>');
  407.  
    }
  408.  
    // console.log(conv_content)
  409.  
    $( '.convBox .mainCon').html(conv_content.join(''));
  410.  
    }
  411.  
    });
  412.  
    $( '.convBox').show();
  413.  
    })
  414.  
    $( document).on('click', '.convBox .close', function () {
  415.  
    $( '.convBox').hide();
  416.  
    });
  417.  
    // 打印
  418.  
    $( '#export').click(function () {
  419.  
    if ($('.page span').text() == '已是最後一頁') {
  420.  
    // method1(tableList,'聊天數據');
  421.  
    method1(tableList, '1.xlsx');
  422.  
    return false;
  423.  
    }
  424.  
     
  425.  
    pageAll =pagesize;
  426.  
    allrecord();
  427.  
    // method1(allrecord(),'美洽對話');
  428.  
    })
  429.  
    });
  430.  
    </script>
  431.  
    <script type="text/javascript" language="javascript">
  432.  
    var idTmr;
  433.  
     
  434.  
    function getExplorer() {
  435.  
    var explorer = window.navigator.userAgent;
  436.  
    //ie
  437.  
    if (explorer.indexOf("MSIE") >= 0) {
  438.  
    return 'ie';
  439.  
    }
  440.  
    //firefox
  441.  
    else if (explorer.indexOf("Firefox") >= 0) {
  442.  
    return 'Firefox';
  443.  
    }
  444.  
    //Chrome
  445.  
    else if (explorer.indexOf("Chrome") >= 0) {
  446.  
    return 'Chrome';
  447.  
    }
  448.  
    //Opera
  449.  
    else if (explorer.indexOf("Opera") >= 0) {
  450.  
    return 'Opera';
  451.  
    }
  452.  
    //Safari
  453.  
    else if (explorer.indexOf("Safari") >= 0) {
  454.  
    return 'Safari';
  455.  
    }
  456.  
    }
  457.  
     
  458.  
    function method1(tableid,name="1.xlsx") { //整個表格拷貝到EXCEL中
  459.  
    if (getExplorer() == 'ie') {
  460.  
    var curTbl = document.getElementById(tableid);
  461.  
    var oXL = new ActiveXObject("Excel.Application");
  462.  
     
  463.  
    //建立AX對象excel
  464.  
    var oWB = oXL.Workbooks.Add();
  465.  
    //獲取workbook對象
  466.  
    var xlsheet = oWB.Worksheets(1);
  467.  
    //激活當前sheet
  468.  
    var sel = document.body.createTextRange();
  469.  
    sel.moveToElementText(curTbl);
  470.  
    //把表格中的內容移到TextRange中
  471.  
    sel.select;
  472.  
    //全選TextRange中內容
  473.  
    sel.execCommand( "Copy");
  474.  
    //複製TextRange中內容
  475.  
    xlsheet.Paste();
  476.  
    //粘貼到活動的EXCEL中
  477.  
    oXL.Visible = true;
  478.  
    //設置excel可見屬性
  479.  
     
  480.  
    try {
  481.  
    var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  482.  
    } catch (e) {
  483.  
    print( "Nested catch caught " + e);
  484.  
    } finally {
  485.  
    oWB.SaveAs(fname);
  486.  
    oWB.Close(savechanges = false);
  487.  
    //xls.visible = false;
  488.  
    oXL.Quit();
  489.  
    oXL = null;
  490.  
    //結束excel進程,退出完成
  491.  
    //window.setInterval("Cleanup();",1);
  492.  
    idTmr = window.setInterval("Cleanup();", 1);
  493.  
     
  494.  
    }
  495.  
     
  496.  
    } else {
  497.  
    tableToExcel(tableid,name)
  498.  
    }
  499.  
    }
  500.  
     
  501.  
    function Cleanup() {
  502.  
    window.clearInterval(idTmr);
  503.  
    CollectGarbage();
  504.  
    }
  505.  
    var tableToExcel = (function() {
  506.  
    var uri = 'data:application/vnd.ms-excel;base64,', 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>{table}</table></body></html>'
  507.  
    , base64 = function(s) {
  508.  
    return window.btoa(unescape(encodeURIComponent(s)))
  509.  
    }
  510.  
    , format = function(s, c) {
  511.  
    return s.replace(/{(\w+)}/g, function(m, p) {
  512.  
    return c[p];
  513.  
    })
  514.  
    }
  515.  
    return function(table, name) {
  516.  
    var ctx = {worksheet:name , table:table}
  517.  
    // console.log(uri + base64(format(template, ctx)))
  518.  
    // return;
  519.  
    // $('#export').attr('href',uri + base64(format(template, ctx)))
  520.  
    window.location.href = uri + base64(format(template, ctx));
  521.  
    }
  522.  
    })()
  523.  
    </script>
  524.  
    </body>
  525.  
     
  526.  
    </html>

https://blog.csdn.net/qiphon3650/article/details/77921087

java

 

如今各大瀏覽器基本都支持data協議,因此咱們可使用該協議去將網頁中的table轉化爲excel下載下來node

  1. 對html 進行base64編碼處理
  2. 編碼後的html內容增長前綴 data:application/vnd.ms-excel; ,便可使瀏覽器將其中的數據當作excel來處理,瀏覽器將提示下載或打開excel文件
    代碼小例:
<html> <head> <meta http-equiv="content-Type" content="text/html;charset=utf-8"/> <script type="text/javascript"> function base64 (content) { return window.btoa(unescape(encodeURIComponent(content))); } function exportOffice(tableID){ var type = 'doc'; var table = document.getElementById(tableID); var excelContent = table.innerHTML; var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+type+"' xmlns='http://www.w3.org/TR/REC-html40'>"; excelFile += "<head>"; excelFile += "<!--[if gte mso 9]>"; excelFile += "<xml>"; excelFile += "<x:ExcelWorkbook>"; excelFile += "<x:ExcelWorksheets>"; excelFile += "<x:ExcelWorksheet>"; excelFile += "<x:Name>"; excelFile += "{worksheet}"; excelFile += "</x:Name>"; excelFile += "<x:WorksheetOptions>"; excelFile += "<x:DisplayGridlines/>"; excelFile += "</x:WorksheetOptions>"; excelFile += "</x:ExcelWorksheet>"; excelFile += "</x:ExcelWorksheets>"; excelFile += "</x:ExcelWorkbook>"; excelFile += "</xml>"; excelFile += "<![endif]-->"; excelFile += "</head>"; excelFile += "<body>"; excelFile += excelContent; excelFile += "</body>"; excelFile += "</html>"; var base64data = "base64," + base64(excelFile); switch(type){ case 'excel': window.open('data:application/vnd.ms-'+type+';'+base64data); break; case 'powerpoint': window.open('data:application/vnd.ms-'+type+';'+base64data); break; } } </script> </head> <body> <table id="targetTable"> <tr align="center"> <th>名次</th> <th>姓名</th> <th>成績</th> </tr> <tr align="center"> <td>1</td> <td>小明</td> <td>100</td> </tr> <tr align="center"> <td>2</td> <td>小紅</td> <td>95.5</td> </tr> </table> </br> <input id="Button1" type="button" value="導出" onclick="exportOffice('targetTable')" /> </body> </html> 
 

連接:https://www.jianshu.com/p/a3642877d590

 
 

這五種方法前四種方法只支持IE瀏覽器,最後一個方法支持當前主流的瀏覽器(火狐,IE,ChromeOpera,Safari

  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head lang="en">
  4.  
    <meta charset="UTF-8">
  5.  
    <title>html 表格導出道</title>
  6.  
    <script language="JavaScript" type="text/javascript">
  7.  
    //第一種方法
  8.  
    function method1(tableid) {
  9.  
     
  10.  
    var curTbl = document.getElementById(tableid);
  11.  
    var oXL = new ActiveXObject("Excel.Application");
  12.  
    var oWB = oXL.Workbooks.Add();
  13.  
    var oSheet = oWB.ActiveSheet;
  14.  
    var sel = document.body.createTextRange();
  15.  
    sel.moveToElementText(curTbl);
  16.  
    sel.select();
  17.  
    sel.execCommand( "Copy");
  18.  
    oSheet.Paste();
  19.  
    oXL.Visible = true;
  20.  
     
  21.  
    }
  22.  
    //第二種方法
  23.  
    function method2(tableid)
  24.  
    {
  25.  
     
  26.  
    var curTbl = document.getElementById(tableid);
  27.  
    var oXL = new ActiveXObject("Excel.Application");
  28.  
    var oWB = oXL.Workbooks.Add();
  29.  
    var oSheet = oWB.ActiveSheet;
  30.  
    var Lenr = curTbl.rows.length;
  31.  
    for (i = 0; i < Lenr; i++)
  32.  
    { var Lenc = curTbl.rows(i).cells.length;
  33.  
    for (j = 0; j < Lenc; j++)
  34.  
    {
  35.  
    oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText;
  36.  
     
  37.  
    }
  38.  
     
  39.  
    }
  40.  
    oXL.Visible = true;
  41.  
    }
  42.  
    //第三種方法
  43.  
    function getXlsFromTbl(inTblId, inWindow){
  44.  
     
  45.  
    try {
  46.  
    var allStr = "";
  47.  
    var curStr = "";
  48.  
    if (inTblId != null && inTblId != "" && inTblId != "null") {
  49.  
     
  50.  
    curStr = getTblData(inTblId, inWindow);
  51.  
     
  52.  
    }
  53.  
    if (curStr != null) {
  54.  
    allStr += curStr;
  55.  
    }
  56.  
     
  57.  
    else {
  58.  
     
  59.  
    alert( "你要導出的表不存在");
  60.  
    return;
  61.  
    }
  62.  
    var fileName = getExcelFileName();
  63.  
    doFileExport(fileName, allStr);
  64.  
     
  65.  
    }
  66.  
     
  67.  
    catch(e) {
  68.  
     
  69.  
    alert( "導出發生異常:" + e.name + "->" + e.description + "!");
  70.  
     
  71.  
    }
  72.  
     
  73.  
    }
  74.  
     
  75.  
    function getTblData(inTbl, inWindow) {
  76.  
     
  77.  
    var rows = 0;
  78.  
    var tblDocument = document;
  79.  
    if (!!inWindow && inWindow != "") {
  80.  
     
  81.  
    if (!document.all(inWindow)) {
  82.  
    return null;
  83.  
    }
  84.  
     
  85.  
    else {
  86.  
    tblDocument = eval(inWindow).document;
  87.  
    }
  88.  
     
  89.  
    }
  90.  
     
  91.  
    var curTbl = tblDocument.getElementById(inTbl);
  92.  
    var outStr = "";
  93.  
    if (curTbl != null) {
  94.  
    for (var j = 0; j < curTbl.rows.length; j++) {
  95.  
    for (var i = 0; i < curTbl.rows[j].cells.length; i++) {
  96.  
     
  97.  
    if (i == 0 && rows > 0) {
  98.  
    outStr += " t";
  99.  
    rows -= 1;
  100.  
    }
  101.  
     
  102.  
    outStr += curTbl.rows[j].cells[i].innerText + "t";
  103.  
    if (curTbl.rows[j].cells[i].colSpan > 1) {
  104.  
    for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {
  105.  
    outStr += " t";
  106.  
    }
  107.  
    }
  108.  
    if (i == 0) {
  109.  
    if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {
  110.  
    rows = curTbl.rows[j].cells[i].rowSpan - 1;
  111.  
    }
  112.  
    }
  113.  
    }
  114.  
    outStr += "rn";
  115.  
    }
  116.  
    }
  117.  
     
  118.  
    else {
  119.  
    outStr = null;
  120.  
    alert(inTbl + "不存在 !");
  121.  
    }
  122.  
    return outStr;
  123.  
    }
  124.  
     
  125.  
    function getExcelFileName() {
  126.  
    var d = new Date();
  127.  
    var curYear = d.getYear();
  128.  
    var curMonth = "" + (d.getMonth() + 1);
  129.  
    var curDate = "" + d.getDate();
  130.  
    var curHour = "" + d.getHours();
  131.  
    var curMinute = "" + d.getMinutes();
  132.  
    var curSecond = "" + d.getSeconds();
  133.  
    if (curMonth.length == 1) {
  134.  
    curMonth = "0" + curMonth;
  135.  
    }
  136.  
     
  137.  
    if (curDate.length == 1) {
  138.  
    curDate = "0" + curDate;
  139.  
    }
  140.  
     
  141.  
    if (curHour.length == 1) {
  142.  
    curHour = "0" + curHour;
  143.  
    }
  144.  
     
  145.  
    if (curMinute.length == 1) {
  146.  
    curMinute = "0" + curMinute;
  147.  
    }
  148.  
     
  149.  
    if (curSecond.length == 1) {
  150.  
    curSecond = "0" + curSecond;
  151.  
    }
  152.  
    var fileName = "table" + "_" + curYear + curMonth + curDate + "_"
  153.  
    + curHour + curMinute + curSecond + ".csv";
  154.  
    return fileName;
  155.  
     
  156.  
    }
  157.  
     
  158.  
    function doFileExport(inName, inStr) {
  159.  
    var xlsWin = null;
  160.  
    if (!!document.all("glbHideFrm")) {
  161.  
    xlsWin = glbHideFrm;
  162.  
    }
  163.  
    else {
  164.  
    var width = 6;
  165.  
    var height = 4;
  166.  
    var openPara = "left=" + (window.screen.width / 2 - width / 2)
  167.  
    + ",top=" + (window.screen.height / 2 - height / 2)
  168.  
    + ",scrollbars=no,width=" + width + ",height=" + height;
  169.  
    xlsWin = window.open("", "_blank", openPara);
  170.  
    }
  171.  
    xlsWin.document.write(inStr);
  172.  
    xlsWin.document.close();
  173.  
    xlsWin.document.execCommand( 'Saveas', true, inName);
  174.  
    xlsWin.close();
  175.  
     
  176.  
    }
  177.  
     
  178.  
    //第四種
  179.  
    function method4(tableid){
  180.  
     
  181.  
    var curTbl = document.getElementById(tableid);
  182.  
    var oXL;
  183.  
    try{
  184.  
    oXL = new ActiveXObject("Excel.Application"); //建立AX對象excel
  185.  
    } catch(e){
  186.  
    alert( "沒法啓動Excel!\n\n若是您確信您的電腦中已經安裝了Excel,"+"那麼請調整IE的安全級別。\n\n具體操做:\n\n"+"工具 → Internet選項 → 安全 → 自定義級別 → 對沒有標記爲安全的ActiveX進行初始化和腳本運行 → 啓用");
  187.  
    return false;
  188.  
    }
  189.  
    var oWB = oXL.Workbooks.Add(); //獲取workbook對象
  190.  
    var oSheet = oWB.ActiveSheet;//激活當前sheet
  191.  
    var sel = document.body.createTextRange();
  192.  
    sel.moveToElementText(curTbl); //把表格中的內容移到TextRange中
  193.  
    sel.select(); //全選TextRange中內容
  194.  
    sel.execCommand( "Copy");//複製TextRange中內容
  195.  
    oSheet.Paste(); //粘貼到活動的EXCEL中
  196.  
    oXL.Visible = true; //設置excel可見屬性
  197.  
    var fname = oXL.Application.GetSaveAsFilename("將table導出到excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  198.  
    oWB.SaveAs(fname);
  199.  
    oWB.Close();
  200.  
    oXL.Quit();
  201.  
    }
  202.  
     
  203.  
     
  204.  
    //第五種方法
  205.  
    var idTmr;
  206.  
    function getExplorer() {
  207.  
    var explorer = window.navigator.userAgent ;
  208.  
    //ie
  209.  
    if (explorer.indexOf("MSIE") >= 0) {
  210.  
    return 'ie';
  211.  
    }
  212.  
    //firefox
  213.  
    else if (explorer.indexOf("Firefox") >= 0) {
  214.  
    return 'Firefox';
  215.  
    }
  216.  
    //Chrome
  217.  
    else if(explorer.indexOf("Chrome") >= 0){
  218.  
    return 'Chrome';
  219.  
    }
  220.  
    //Opera
  221.  
    else if(explorer.indexOf("Opera") >= 0){
  222.  
    return 'Opera';
  223.  
    }
  224.  
    //Safari
  225.  
    else if(explorer.indexOf("Safari") >= 0){
  226.  
    return 'Safari';
  227.  
    }
  228.  
    }
  229.  
    function method5(tableid) {
  230.  
    if(getExplorer()=='ie')
  231.  
    {
  232.  
    var curTbl = document.getElementById(tableid);
  233.  
    var oXL = new ActiveXObject("Excel.Application");
  234.  
    var oWB = oXL.Workbooks.Add();
  235.  
    var xlsheet = oWB.Worksheets(1);
  236.  
    var sel = document.body.createTextRange();
  237.  
    sel.moveToElementText(curTbl);
  238.  
    sel.select();
  239.  
    sel.execCommand( "Copy");
  240.  
    xlsheet.Paste();
  241.  
    oXL.Visible = true;
  242.  
     
  243.  
    try {
  244.  
    var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  245.  
    } catch (e) {
  246.  
    print( "Nested catch caught " + e);
  247.  
    } finally {
  248.  
    oWB.SaveAs(fname);
  249.  
    oWB.Close(savechanges = false);
  250.  
    oXL.Quit();
  251.  
    oXL = null;
  252.  
    idTmr = window.setInterval("Cleanup();", 1);
  253.  
    }
  254.  
     
  255.  
    }
  256.  
    else
  257.  
    {
  258.  
    tableToExcel(tableid)
  259.  
    }
  260.  
    }
  261.  
    function Cleanup() {
  262.  
    window.clearInterval(idTmr);
  263.  
    CollectGarbage();
  264.  
    }
  265.  
    var tableToExcel = (function() {
  266.  
    var uri = 'data:application/vnd.ms-excel;base64,',
  267.  
    template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',
  268.  
    base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) },
  269.  
    format = function(s, c) {
  270.  
    return s.replace(/{(\w+)}/g,
  271.  
    function(m, p) { return c[p]; }) }
  272.  
    return function(table, name) {
  273.  
    if (!table.nodeType) table = document.getElementById(table)
  274.  
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
  275.  
    window.location.href = uri + base64(format(template, ctx))
  276.  
    }
  277.  
    })()
  278.  
     
  279.  
    </script>
  280.  
    </head>
  281.  
    <body>
  282.  
     
  283.  
    <div >
  284.  
    <button type="button" onclick="method1('tableExcel')">導出Excel方法一</button>
  285.  
    <button type="button" onclick="method2('tableExcel')">導出Excel方法二</button>
  286.  
    <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv')">導出Excel方法三</button>
  287.  
    <button type="button" onclick="method4('tableExcel')">導出Excel方法四</button>
  288.  
    <button type="button" onclick="method5('tableExcel')">導出Excel方法五</button>
  289.  
    </div>
  290.  
    <div id="myDiv">
  291.  
    <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
  292.  
    <tr>
  293.  
    <td colspan="5" align="center">html 表格導出道Excel</td>
  294.  
    </tr>
  295.  
    <tr>
  296.  
    <td>列標題1</td>
  297.  
    <td>列標題2</td>
  298.  
    <td>類標題3</td>
  299.  
    <td>列標題4</td>
  300.  
    <td>列標題5</td>
  301.  
    </tr>
  302.  
    <tr>
  303.  
    <td>aaa</td>
  304.  
    <td>bbb</td>
  305.  
    <td>ccc</td>
  306.  
    <td>ddd</td>
  307.  
    <td>eee</td>
  308.  
    </tr>
  309.  
    <tr>
  310.  
    <td>AAA</td>
  311.  
    <td>BBB</td>
  312.  
    <td>CCC</td>
  313.  
    <td>DDD</td>
  314.  
    <td>EEE</td>
  315.  
    </tr>
  316.  
    <tr>
  317.  
    <td>FFF</td>
  318.  
    <td>GGG</td>
  319.  
    <td>HHH</td>
  320.  
    <td>III</td>
  321.  
    <td>JJJ</td>
  322.  
    </tr>
  323.  
    </table>
  324.  
    </div>
  325.  
    </body>
  326.  
    </html>

今天上來發現,好多人,會遇到文件名,格式等問題。這裏添加一種方法。兼容性我沒有測試,你們能夠試下,不過須要利用JQ直接貼代碼了。jquery 引入文件在http://download.csdn.net/download/aa122273328/10103711  注意必定要引jquery-3.2.1.min.js,jquery.table2excel.js對應的文件。jquery-3.2.1.min.js這個看你對應的文件版本,不重要。若有問題,歡迎批評指導。

 
  1.  
    <!DOCTYPE html>
  2.  
    <html>
  3.  
    <head lang="en">
  4.  
    <meta charset="UTF-8">
  5.  
    <title>html 表格導出道</title>
  6.  
    <script src="js/vendor/jquery-3.2.1.min.js"></script>
  7.  
    <script src="jquery.table2excel.js"></script>
  8.  
    <script language="JavaScript" type="text/javascript">
  9.  
     
  10.  
    $( document).ready(function () {
  11.  
    $( "#btnExport").click(function () {
  12.  
    $( "#tableExcel").table2excel({
  13.  
    exclude : ".noExl", //過濾位置的 css 類名
  14.  
    filename : "你想說啥" + new Date().getTime() + ".xls", //文件名稱
  15.  
    name: "Excel Document Name.xlsx",
  16.  
    exclude_img: true,
  17.  
    exclude_links: true,
  18.  
    exclude_inputs: true
  19.  
     
  20.  
    });
  21.  
    });
  22.  
    });
  23.  
     
  24.  
    </script>
  25.  
    </head>
  26.  
    <body>
  27.  
     
  28.  
    <div >
  29.  
     
  30.  
    <button type="button" id="btnExport" onclick="method5('tableExcel')">導出Excel</button>
  31.  
    </div>
  32.  
    <div id="myDiv">
  33.  
    <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
  34.  
    <tr>
  35.  
    <td colspan="5" align="center">html 表格導出道Excel</td>
  36.  
    </tr>
  37.  
    <tr>
  38.  
    <td>列標題1</td>
  39.  
    <td>列標題2</td>
  40.  
    <td>類標題3</td>
  41.  
    <td>列標題4</td>
  42.  
    <td>列標題5</td>
  43.  
    </tr>
  44.  
    <tr>
  45.  
    <td>aaa</td>
  46.  
    <td>bbb</td>
  47.  
    <td>ccc</td>
  48.  
    <td>ddd</td>
  49.  
    <td>eee</td>
  50.  
    </tr>
  51.  
    <tr>
  52.  
    <td>AAA</td>
  53.  
    <td>BBB</td>
  54.  
    <td>CCC</td>
  55.  
    <td>DDD</td>
  56.  
    <td>EEE</td>
  57.  
    </tr>
  58.  
    <tr>
  59.  
    <td>FFF</td>
  60.  
    <td>GGG</td>
  61.  
    <td>HHH</td>
  62.  
    <td>III</td>
  63.  
    <td>JJJ</td>
  64.  
    </tr>
  65.  
    </table>
  66.  
    </div>
  67.  
    </body>
  68.  
    </html>
 
   
[html]  view plain  copy
 
  1.   
 
   
https://blog.csdn.net/aa122273328/article/details/50388673
 
    
   
 
   
 
  

 

有時候咱們須要把網頁中的數據導出excel格式來,那麼咱們用下面兩種方法能夠完成。jquery

第一種.自寫代碼

<html> <head> <meta http-equiv="content-Type" content="text/html;charset=utf-8"/> <script type="text/javascript"> function base64 (content) { return window.btoa(unescape(encodeURIComponent(content))); } /* *@tableId: table的Id *@fileName: 要生成excel文件的名字(不包括後綴,可隨意填寫) */ function tableToExcel(tableID,fileName){ var table = document.getElementById(tableID); var excelContent = table.innerHTML; var excelFile = "<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'>"; excelFile += "<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>"; excelFile += "<body><table>"; excelFile += excelContent; excelFile += "</table></body>"; excelFile += "</html>"; var link = "data:application/vnd.ms-excel;base64," + base64(excelFile); var a = document.createElement("a"); a.download = fileName+".xlsx"; a.href = link; a.click(); } </script> </head> <body> <button type="button" onclick="tableToExcel('item','data')">導出</button> <table id="item"> <tr> <th>編號</th> <th>姓名</th> <th>年齡</th> </tr> <tr> <td>1</td> <td>小明</td> <td>19</td> </tr> <tr> <td>2</td> <td>小芳</td> <td>20</td> </tr> <tr> <td>3</td> <td>大軍</td> <td>22</td> </tr> </table> </body> </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

**git

第二種.jquery插件

** 
首先要先下載一個jquery.table2excel.js插件(網上搜搜),而後使用。github

<!doctype html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>table2excel</title> <link rel="stylesheet" href="http://libs.baidu.com/bootstrap/3.2.0/css/bootstrap.min.css"> </head> <body> <header class="jq22-header"> <h4>table2excel-可將HTML表格內容導出到Excel中的jQuery插件 <span>jQuery Plugin to export HTML tabled to Excel Spreadsheet Compatible Files</span></h4> </header> <section class="jq22-container"> <div class="container" style="padding:30px 0"> <div class="row"> <div class="md-col-8"> <div class="table-responsive table2excel" data-tableName="Test Table 1"> <table class="table table-striped table-bordered table-hover"> <thead> <tr class="noExl"> <td class="danger">帶<code>noExl</code>class的行不會被輸出到excel中</td> <td class="danger">帶<code>noExl</code>class的行不會被輸出到excel中</td> </tr> <tr> <td class="success">這一行會被導出到excel中</td> <td class="success">這一行會被導出到excel中</td> </tr> </thead> <tbody> <tr> <td>單元格1-1</td> <td>單元格1-2</td> </tr> <tr> <td>單元格2-1</td> <td>單元格2-2</td> </tr> <tr> <td>單元格3-1</td> <td>單元格3-2</td> </tr> </tbody> <tfoot> <tr> <td colspan="2" class="warning">合併2個單元格</td> </tr> </tfoot> </table> </div> </div> </div> <button id="btn" class="btn btn-primary">點擊這裏將表格內容導出到excel中</button> </div> </section> <script src="http://www.jq22.com/jquery/1.11.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js"><\/script>')</script> <script src="dist/jquery.table2excel.js"></script> <script> $(function() { $("#btn").click(function(){ $(".table2excel").table2excel({ exclude: ".noExl", name: "Excel Document Name", filename: "myFileName", exclude_img: true, exclude_links: true, exclude_inputs: true }); }); }); </script> </body> </html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

詳情請瀏覽:html中table導出Excel

 https://blog.csdn.net/jesslu/article/details/77866040
 
 
 

jquery-table2excel是一款能夠將HTML表格的內容導出到微軟Excel電子表格中的jQuery插件。該插件能夠根據你的須要導出表格中的內容,不須要的行能夠不導出。它文件體積小,使用很是方便。

jquery-table2excel插件的github地址爲:https://github.com/rainabba/jquery-table2excel

注意導出的Excel文件的格式,默認導出爲.xlsx格式的excel文件,須要excel2010以上的版本才能打開,若是是使用低版本的excel,能夠手動將文件擴展名修改成.xls

 使用方法

使用table2excel表格插件須要在頁面中引入jquery和jquery.table2excel.js文件。

 

  1.  
    <script type= "text/javascript" src="js/jquery.min.js"></script>
  2.  
    <script type= "text/javascript" src="js/jquery.table2excel.js"></script>


若是表格中的某一行不須要導出到Excel中,能夠爲這一行添加.noExl class類,該class類會在插件初始化時經過參數被指定爲不被導出的數據。

 初始化插件

在頁面DOM元素加載中完畢以後,能夠經過下面的方法來初始化table2excel插件。

 

  1.  
    $( "#table2excel").table2excel({
  2.  
    // 不被導出的表格行的CSS class類
  3.  
    exclude: ".noExl",
  4.  
    // 導出的Excel文檔的名稱
  5.  
    name: "Excel Document Name",
  6.  
    // Excel文件的名稱
  7.  
    filename: "myExcelTable"
  8.  
    });


配置參數

table2excel插件的可用配置參數有:

  • exclude:不被導出的表格行的CSS class類。
  • name:導出的Excel文檔的名稱。
  • filename:Excel文件的名稱。
  • exclude_img:是否導出圖片。
  • exclude_links:是否導出超連接
  • exclude_inputs:是否導出輸入框中的內容。
示例:
  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
     
  6.  
    </head>
  7.  
    <body>
  8.  
    <table border="0" cellspacing="0" cellpadding="0" id="datatable" class="xd_table_sj">
  9.  
     
  10.  
    <tbody>
  11.  
    <tr>
  12.  
    <td><div align="center" id="titlelable">起始時間</div></td>
  13.  
    <td><div align="center" id="titlelable">通訊地點</div></td>
  14.  
    <td><div align="center" id="titlelable">上網方式</div></td>
  15.  
    <td><div align="center" id="titlelable">總時長</div></td>
  16.  
    <td><div align="center" id="titlelable">總流量</div></td>
  17.  
    <td><div align="center" id="titlelable">套餐優惠</div></td>
  18.  
    <td><div align="center" id="titlelable">優惠或減免</div></td>
  19.  
    <td><div align="center" id="titlelable">通訊費</div></td>
  20.  
    <td><div align="center" id="titlelable">終端類型</div></td>
  21.  
    </tr>
  22.  
     
  23.  
     
  24.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  25.  
    <td>10-01 01:57:05</td>
  26.  
    <td></td>
  27.  
    <td>CMNET</td>
  28.  
    <td>0秒</td>
  29.  
    <td>0.001</td>
  30.  
    <td>校園4G套餐-400M國內流量</td>
  31.  
    <td></td>
  32.  
    <td>0.00</td>
  33.  
    <td></td>
  34.  
    </tr>
  35.  
     
  36.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  37.  
    <td>10-01 01:58:55</td>
  38.  
    <td></td>
  39.  
    <td>CMNET</td>
  40.  
    <td>0秒</td>
  41.  
    <td>0.007</td>
  42.  
    <td>校園4G套餐-400M國內流量</td>
  43.  
    <td></td>
  44.  
    <td>0.00</td>
  45.  
    <td></td>
  46.  
    </tr>
  47.  
     
  48.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  49.  
    <td>10-01 07:00:00</td>
  50.  
    <td></td>
  51.  
    <td>CMNET</td>
  52.  
    <td>0秒</td>
  53.  
    <td>0.001</td>
  54.  
    <td>校園4G套餐-400M國內流量</td>
  55.  
    <td></td>
  56.  
    <td>0.00</td>
  57.  
    <td></td>
  58.  
    </tr>
  59.  
     
  60.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  61.  
    <td>10-01 07:23:19</td>
  62.  
    <td></td>
  63.  
    <td>CMNET</td>
  64.  
    <td>0秒</td>
  65.  
    <td>0.084</td>
  66.  
    <td>校園4G套餐-400M國內流量</td>
  67.  
    <td></td>
  68.  
    <td>0.00</td>
  69.  
    <td></td>
  70.  
    </tr>
  71.  
     
  72.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  73.  
    <td>10-01 08:16:31</td>
  74.  
    <td></td>
  75.  
    <td>CMNET</td>
  76.  
    <td>0秒</td>
  77.  
    <td>0.001</td>
  78.  
    <td>校園4G套餐-400M國內流量</td>
  79.  
    <td></td>
  80.  
    <td>0.00</td>
  81.  
    <td></td>
  82.  
    </tr>
  83.  
     
  84.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  85.  
    <td>10-01 08:16:39</td>
  86.  
    <td></td>
  87.  
    <td>CMNET</td>
  88.  
    <td>0秒</td>
  89.  
    <td>0.06</td>
  90.  
    <td>校園4G套餐-400M國內流量</td>
  91.  
    <td></td>
  92.  
    <td>0.00</td>
  93.  
    <td></td>
  94.  
    </tr>
  95.  
     
  96.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  97.  
    <td>10-01 08:28:44</td>
  98.  
    <td></td>
  99.  
    <td>CMNET</td>
  100.  
    <td>0秒</td>
  101.  
    <td>0.002</td>
  102.  
    <td>校園4G套餐-400M國內流量</td>
  103.  
    <td></td>
  104.  
    <td>0.00</td>
  105.  
    <td></td>
  106.  
    </tr>
  107.  
     
  108.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  109.  
    <td>10-01 08:34:50</td>
  110.  
    <td></td>
  111.  
    <td>CMNET</td>
  112.  
    <td>0秒</td>
  113.  
    <td>0.259</td>
  114.  
    <td>校園4G套餐-400M國內流量</td>
  115.  
    <td></td>
  116.  
    <td>0.00</td>
  117.  
    <td></td>
  118.  
    </tr>
  119.  
     
  120.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  121.  
    <td>10-01 08:34:50</td>
  122.  
    <td></td>
  123.  
    <td>CMNET</td>
  124.  
    <td>0秒</td>
  125.  
    <td>1.26</td>
  126.  
    <td>校園4G套餐-400M國內流量</td>
  127.  
    <td></td>
  128.  
    <td>0.00</td>
  129.  
    <td></td>
  130.  
    </tr>
  131.  
     
  132.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  133.  
    <td>10-01 09:54:53</td>
  134.  
    <td></td>
  135.  
    <td>CMNET</td>
  136.  
    <td>0秒</td>
  137.  
    <td>1.357</td>
  138.  
    <td>校園4G套餐-400M國內流量</td>
  139.  
    <td></td>
  140.  
    <td>0.00</td>
  141.  
    <td></td>
  142.  
    </tr>
  143.  
     
  144.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  145.  
    <td>10-01 09:56:29</td>
  146.  
    <td></td>
  147.  
    <td>CMNET</td>
  148.  
    <td>0秒</td>
  149.  
    <td>0.003</td>
  150.  
    <td>校園4G套餐-400M國內流量</td>
  151.  
    <td></td>
  152.  
    <td>0.00</td>
  153.  
    <td></td>
  154.  
    </tr>
  155.  
     
  156.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  157.  
    <td>10-01 09:56:31</td>
  158.  
    <td></td>
  159.  
    <td>CMNET</td>
  160.  
    <td>0秒</td>
  161.  
    <td>0.009</td>
  162.  
    <td>校園4G套餐-400M國內流量</td>
  163.  
    <td></td>
  164.  
    <td>0.00</td>
  165.  
    <td></td>
  166.  
    </tr>
  167.  
     
  168.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  169.  
    <td>10-01 09:56:33</td>
  170.  
    <td></td>
  171.  
    <td>CMNET</td>
  172.  
    <td>0秒</td>
  173.  
    <td>0.583</td>
  174.  
    <td>校園4G套餐-400M國內流量</td>
  175.  
    <td></td>
  176.  
    <td>0.00</td>
  177.  
    <td></td>
  178.  
    </tr>
  179.  
     
  180.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  181.  
    <td>10-01 10:27:16</td>
  182.  
    <td></td>
  183.  
    <td>CMNET</td>
  184.  
    <td>0秒</td>
  185.  
    <td>0.001</td>
  186.  
    <td>校園4G套餐-400M國內流量</td>
  187.  
    <td></td>
  188.  
    <td>0.00</td>
  189.  
    <td></td>
  190.  
    </tr>
  191.  
     
  192.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  193.  
    <td>10-01 10:28:58</td>
  194.  
    <td></td>
  195.  
    <td>CMNET</td>
  196.  
    <td>0秒</td>
  197.  
    <td>0.004</td>
  198.  
    <td>校園4G套餐-400M國內流量</td>
  199.  
    <td></td>
  200.  
    <td>0.00</td>
  201.  
    <td></td>
  202.  
    </tr>
  203.  
     
  204.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  205.  
    <td>10-01 12:44:12</td>
  206.  
    <td></td>
  207.  
    <td>CMNET</td>
  208.  
    <td>0秒</td>
  209.  
    <td>0.001</td>
  210.  
    <td>校園4G套餐-400M國內流量</td>
  211.  
    <td></td>
  212.  
    <td>0.00</td>
  213.  
    <td></td>
  214.  
    </tr>
  215.  
     
  216.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  217.  
    <td>10-01 12:45:41</td>
  218.  
    <td></td>
  219.  
    <td>CMNET</td>
  220.  
    <td>0秒</td>
  221.  
    <td>0.411</td>
  222.  
    <td>校園4G套餐-400M國內流量</td>
  223.  
    <td></td>
  224.  
    <td>0.00</td>
  225.  
    <td></td>
  226.  
    </tr>
  227.  
     
  228.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  229.  
    <td>10-01 12:57:42</td>
  230.  
    <td></td>
  231.  
    <td>CMNET</td>
  232.  
    <td>0秒</td>
  233.  
    <td>0.024</td>
  234.  
    <td>校園4G套餐-400M國內流量</td>
  235.  
    <td></td>
  236.  
    <td>0.00</td>
  237.  
    <td></td>
  238.  
    </tr>
  239.  
     
  240.  
    <tr bgcolor="#EFFEDD" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#EFFEDD'" style="background: rgb(239, 254, 221);">
  241.  
    <td>10-01 12:57:50</td>
  242.  
    <td></td>
  243.  
    <td>CMNET</td>
  244.  
    <td>0秒</td>
  245.  
    <td>0.009</td>
  246.  
    <td>校園4G套餐-400M國內流量</td>
  247.  
    <td></td>
  248.  
    <td>0.00</td>
  249.  
    <td></td>
  250.  
    </tr>
  251.  
     
  252.  
    <tr bgcolor="#ffffff" onmouseover="this.style.background='#D2FCA0'" onmouseout="this.style.background='#ffffff'" style="background: rgb(255, 255, 255);">
  253.  
    <td>10-01 12:57:52</td>
  254.  
    <td></td>
  255.  
    <td>CMNET</td>
  256.  
    <td>0秒</td>
  257.  
    <td>0.007</td>
  258.  
    <td>校園4G套餐-400M國內流量</td>
  259.  
    <td></td>
  260.  
    <td>0.00</td>
  261.  
    <td></td>
  262.  
    </tr>
  263.  
     
  264.  
    </tbody>
  265.  
    </table>
  266.  
    <button>導出EXCEL</button>
  267.  
    <script src="js/jquery-3.2.1.js"></script>
  268.  
     
  269.  
    <script src="js/jquery.table2excel.js"></script>
  270.  
    <script>
  271.  
    $( 'button').click(function(){
  272.  
    console.log(1)
  273.  
    $( "#datatable").table2excel({
  274.  
    exclude: ".noExl",
  275.  
    name: "Excel Document Name",
  276.  
    filename: "myFileName",
  277.  
    exclude_img: true,
  278.  
    exclude_links: true,
  279.  
    exclude_inputs: true
  280.  
    });
  281.  
    })
  282.  
    </script>
  283.  
    </body>
  284.  
    </html>


 https://blog.csdn.net/hefeng6500/article/details/78449436

 

 

第一部分:html+js

1.須要使用的表格數據(先不考慮動態生成的table)

複製代碼
<table class="table tableStyles" id="tables">
        <caption>不正經的統計表</caption><!--能夠生成表格的標題-->
        <thead>
            <tr>
                <th>品牌</th>
                <th>門店</th>
                <th>本週回訪</th>
                <th>本月回訪</th>
                <th>總回訪</th>
                <th>本週成交數</th>
                <th>本月成交數</th>
                <th>總成交數</th>
                <th>異常量</th>
                <th>成交轉化率</th>
                <th>經手人/th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td rowspan="3">華爲</td>
                <td>華爲深圳店</td>
                <td>20</td>
                <td>80</td>
                <td>500</td>
                <td>1</td>
                <td>3</td>
                <td>20</td>
                <td>1</td>
                <td>4.0%</td>
                <td>黃生</td>
            </tr>
            <tr>
                <td>華爲東莞店</td>
                <td>20</td>
                <td>80</td>
                <td>500</td>
                <td>1</td>
                <td>3</td>
                <td>20</td>
                <td>1</td>
                <td>4.0%</td>
                <td>黃生</td>
            </tr>
            <tr>
                <td>華爲佛山店</td>
                <td>20</td>
                <td>80</td>
                <td>500</td>
                <td>1</td>
                <td>3</td>
                <td>20</td>
                <td>1</td>
                <td>4.0%</td>
                <td>黃生</td>
            </tr>
            <tr>
                <td rowspan="3">小米</td>
                <td>米家深圳店</td>
                <td>20</td>
                <td>80</td>
                <td>500</td>
                <td>1</td>
                <td>3</td>
                <td>20</td>
                <td>1</td>
                <td>4.0%</td>
                <td>林生</td>
            </tr>
        </tbody>
    </table>
複製代碼

2.Js代碼

①利用html5的download屬性,點擊下載該文件

<a id="dlink"  style="display:none;"></a>
<input type="button" onclick="tableToExcel('tables', 'name', 'myfile.xls')" value="Export to Excel">
複製代碼
<script type="text/javascript">
        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,',
                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>{table}</table></body></html>',
                base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
                format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
            return function (table, name, filename) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    
                document.getElementById("dlink").href = uri + base64(format(template, ctx));
                document.getElementById("dlink").download = filename;
                document.getElementById("dlink").click();
            }
        })()
    </script>
複製代碼

②建立ActiveXObject對象複製到表格中

<input id="Button1" type="button" value="導出EXCEL" onclick="javascript:excels('tables')" />
複製代碼
<script type="text/javascript">
        var timer;
        function getExplorer(){//獲取瀏覽器
            var explorer=window.navigator.userAgent;
            if(explorer.indexOf("MSIE") >= 0|| (explorer.indexOf("Windows NT 6.1;") >= 0 && explorer.indexOf("Trident/7.0;") >= 0)){
                return 'ie';
            }else if (explorer.indexOf("Firefox") >= 0) {
                return 'Firefox';
            }else if(explorer.indexOf("Chrome") >= 0){
                return 'Chrome';
            }else if(explorer.indexOf("Opera") >= 0){
                return 'Opera';
            }else if(explorer.indexOf("Safari") >= 0){
                return 'Safari';
            }
        }
        function excels(table){
            if(getExplorer()=='ie'){
                var curTbl = document.getElementById(table);
                var oXl=new ActiveXObject("Excel.Application");//建立AX對象excel 
                var oWB = oXL.Workbooks.Add();//獲取workbook對象
                var xlsheet = oWB.Worksheets(1);//激活當前sheet
                var sel = document.body.createTextRange();
                sel.moveToElementText(curTbl);//把表格中的內容移到TextRange中 
                sel.select;//全選TextRange中內容
                sel.execCommand("Copy");//複製TextRange中內容
                xlsheet.Paste();//粘貼到活動的EXCEL中
                oXL.Visible = true;//設置excel可見屬性
                try{
                    var filename = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
                }catch(e){
                    window.print("Nested catch caught " + e);
                }finally{
                    oWB.SaveAs(filename);
                    oWB.Close(savechanges = false);
                    oXL.Quit();
                    oXL = null;//結束excel進程,退出完成
                    timer = window.setInterval("Cleanup();", 1);
                }
            }else{
                tableToExcel("tables");
            }
        }
        function Cleanup(){
            window.clearInterval(timer);
            CollectGarbage();//CollectGarbage,是IE的一個特有屬性,用於釋放內存的
        }
        var tableToExcel=(function(){
            var uri = 'data:application/vnd.ms-excel;base64,',
                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>{table}</table></body></html>',
                base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) },
                format = function(s, c) {
                    return s.replace(/{(\w+)}/g,
                    function(m, p) { return c[p]; }) };
            return function(table, name) {
                if (!table.nodeType) table = document.getElementById(table);
                var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
                window.location.href = uri + base64(format(template, ctx))
            }
        })();
    </script>
複製代碼

 

第二部分:分析測試
測試環境(谷歌,火狐,IE,EDGE,QQ瀏覽器)

①.真正起到做用的是a標籤的屬性,input按鈕只是起到了一個過渡到download屬性的做用;

    其中有編碼解碼,須要注意中文亂碼狀況;

    測試只有谷歌和火狐起做用,且只有谷歌下載的文件名是「下載.xls」,火狐的文件名像是編碼後的~

 雙核瀏覽器固然也只有chrome內核下有效果~~

 我比較喜歡的一點,html中合併的單元格導出到excel中繼續保留合併效果~~

    谷歌截圖:

    火狐截圖:

 ②.主要是利用AX對象建立excel

  在IE下不行,會提示錯誤「不能使用啥對象什麼什麼」

  難道是須要安裝Office軟件?沒試過。。

 

這幾個瀏覽器中,谷歌的體驗稍微好一點,還能夠本身帶個命名什麼的~~,其餘體驗都不是很友好~~

還有其餘的問題是我繼續須要想的,表格內容分頁狀況導出?篩選條件後導出所有?等等等~

附上源碼註釋地址:https://github.com/Chuyue0/javascript-demo/blob/master/tableExporeExcel.html

 開發過程當中有不少預料不到的事,繼續加油吧!

 

~~~~~~~~~~~~剩到最後的解決辦法是利用插件~~~~~~~~~~~~

好比github上的

1020 Star:https://github.com/kayalshri/tableExport.jquery.plugin

270 Star:https://github.com/clarketm/TableExport

159 Star:https://github.com/huanz/tableExport

說明一下,星星多的插件是有base64編碼,因此還額外須要js腳本!

我的比較喜歡最少星星的庫,感受明瞭清晰,能夠按需加載~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

 

js實現table導出Excel,保留table樣式

 

瀏覽器環境:谷歌瀏覽器

1.在導出Excel的時候,保存table的樣式,有2種方法,①是在table的行內寫style樣式,②是在模板裏面添加樣式

2.第一種方式:行內添加樣式

<td style="font-size: 18px">公司一</td>

效果:

完整代碼:

複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table td {
            font-size: 12px;
            width: 200px;
            height: 30px;
            text-align: center;
            background-color: #4f891e;
            color: #ffffff;
        }
    </style>
</head>
<body>
<a download="table導出Excel" id="excelOut" href="#">table導出Excel</a>
<table cellspacing="0" cellpadding="0" border="1" id="tableToExcel">
    <thead>
    <tr>
        <td style="font-size: 18px">公司一</td>
        <td>公司二一</td>
        <td>公司三</td>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td colspan="3">共計</td>
    </tr>
    </tbody>
</table>
<script>
    window.onload = function () {
        tableToExcel('tableToExcel', '下載模板')
    };
    //base64轉碼
    var base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    //替換table數據和worksheet名字
    var format = function (s, c) {
        return s.replace(/{(\w+)}/g,
            function (m, p) {
                return c[p];
            });
    }
    function tableToExcel(tableid, sheetName) {
        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"><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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            '' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
        if (!tableid.nodeType) tableid = document.getElementById(tableid);
        var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
        document.getElementById("excelOut").href = uri + base64(format(template, ctx));
    }

</script>
</body>
</html>
複製代碼

3.第二種方式:在模板裏面裏面添加樣式

在這裏面添加的樣式excel就能找到和識別了

複製代碼
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"><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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            '' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
複製代碼

完整代碼:

複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table td {
            font-size: 12px;
            width: 200px;
            height: 30px;
            text-align: center;
            background-color: #4f891e;
            color: #ffffff;
        }
    </style>
</head>
<body>
<a download="table導出Excel" id="excelOut" href="#">table導出Excel</a>
<table cellspacing="0" cellpadding="0" border="1" id="tableToExcel">
    <thead>
    <tr>
        <td >公司一</td>
        <td>公司二一</td>
        <td>公司三</td>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td colspan="3">共計</td>
    </tr>
    </tbody>
</table>
<script>
    window.onload = function () {
        tableToExcel('tableToExcel', '下載模板')
    };
    //base64轉碼
    var base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    //替換table數據和worksheet名字
    var format = function (s, c) {
        return s.replace(/{(\w+)}/g,
            function (m, p) {
                return c[p];
            });
    }
    function tableToExcel(tableid, sheetName) {
        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"><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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            '' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
        if (!tableid.nodeType) tableid = document.getElementById(tableid);
        var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
        document.getElementById("excelOut").href = uri + base64(format(template, ctx));
    }

</script>
</body>
</html>
複製代碼

注意:若是同時添加了行內樣式和模板樣式,行內的樣式會覆蓋模板的樣式

 

 

大佬!咱們怎麼變成是html格式的呢!導出的並非excel格式
!你是否是下載的時候沒有設置文件的後綴?

a標籤的download="table導出Exce.xls" 
如<a download="table導出Exce.xls" id="excelOut" href="#">table導出Excel</a>

問題一 若是沒有安裝 office 導出來 

安裝 office 就默認指定了後綴 

 

 問題二   文件格式和擴展名不匹配。文件可能已損壞或不安全 除非您信任其來源

沒解決 不影響功能

 office 打開報 文件格式和擴展名不匹配。文件可能已損壞或不安全 除非您信任來源 不然請勿打開,是否仍要打開它

相關文章
相關標籤/搜索