如何在vue中将html导出为ex cel?

问题描述 投票:0回答:1

我想将我的html表导出为ex​​cel。这是我尝试过的:

<div id="app">
   <table id="table" border="1">
     <tr>
       <td>
          Foo
       </td>
       <td>
          Bar
       </td>
     </tr>
   </table>
   <a id="downloadLink" @click="exportF(this)">Export to excel</a>
</div>
new Vue({
    el: '#app',
    data: {

    },
    methods: {
      exportF(elem) {    
        var table = document.getElementById("table");
        var html = table.outerHTML;
        var url = 'data:application/vnd.ms-excel,' + escape(html); 
        // Set your html table into url 
        elem.setAttribute("href", url);
        elem.setAttribute("download", "export.xls"); 
        return false;
     }
   }
})
javascript vue.js
1个回答
0
投票

小例子:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

<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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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>

Updated Fiddle Here.

© www.soinside.com 2019 - 2024. All rights reserved.