html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式

先上代码

 

  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/51098522

github也有写好的插件:

 

  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/1190000000336643

我的html实例

 

  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

 

现在各大浏览器基本都支持data协议,所以我们可以使用该协议去将网页中的table转化为excel下载下来

  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格式来,那么我们用下面两种方法可以完成。

第一种.自写代码

<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

**

第二种.jquery插件

** 
首先要先下载一个jquery.table2excel.js插件(网上搜搜),然后使用。

<!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 打开报 文件格式和扩展名不匹配。文件可能已损坏或不安全 除非您信任来源 否则请勿打开,是否仍要打开它

posted @ 2018-09-04 14:21  ~雨落忧伤~  阅读(1251)  评论(0编辑  收藏  举报