Convert HTML table to Excel file in pure JavaScrip

2019-08-30 09:39发布

This question already has an answer here:

I couldn't find an existing question/answers on Stack Overflow for my particular issue so I'm posting this. I have an application written in HTML and jQuery/JavaScript. I need to export an HTML table into an Excel sheet using the jsxlsx (sheetsjs) plugin. I tried replicating their example to convert HTML table to Excel but the program errors out. Here's what I currently have:

My HTML code is inside a coldfusion page called books.cfm. I have my JavaScript in a file called Utils.js. These are:

function s2ab(s) { 
  var buf = new ArrayBuffer(s.length); 
  var view = new Uint8Array(buf); 
  for (var i=0; i<s.length; i++) 
    view[i] = s.charCodeAt(i) & 0xFF; 
    return buf; 
}
 
function convertToExcel(event){
  event.preventDefault();
  console.log("button clicked");
  var wb = XLSX.utils.table_to_book( $("#exceltable"), {sheet:"Exported 
    table"} );
  saveAs(new Blob([s2ab(wb)],{type:"application/octet-stream"}), 
   'test.xlsx');
}
<html>
<head>
  <script src="libs/jquery.min.js"></script>
  <script src="libs/sheets/xlsx.full.min.js"></script>
  <script src="libs/FileSaver/FileSaver.min.js"></script>
  <script src="scripts/Utils.js"></script>
</head>
<body>
  <table id="myTable">
    <tr>
      <td>ID</td>
      <td>Name</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Johnny</td>
    </tr>
  </table>
 <button id="myBtn" onclick="convertToExcel(event)">Export</button>
</body>
</html>

When I run the above code and click on the button to convert to Excel, I get the following error:

**Uncaught TypeError: e.getElementsByTagName is not a function
at GC (xlsx.full.min.js:20)
at Object.jC [as table_to_book] (xlsx.full.min.js:20)
at exportErrsToExcel (Util.js:1227)
at HTMLButtonElement.onclick (books.cfm:18)**

Note: I got the above JavaScript code from this site.

1条回答
forever°为你锁心
2楼-- · 2019-08-30 10:10

New Answer With SheetJS Working code :

<script type="text/javascript" src="//unpkg.com/xlsx/dist/shim.min.js"></script>
<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

<script type="text/javascript" src="//unpkg.com/blob.js@1.0.1/Blob.js"></script>
<script type="text/javascript" src="//unpkg.com/file-saver@1.3.3/FileSaver.js"></script>


<div id="container2">
  <title>SheetJS Table Export</title>
  <table id="data-table">
    <tr>
      <td>ID</td>
      <td>Name</td>
    </tr>
    <tr>
      <td>1</td>
      <td>Johnny</td>
    </tr>
  </table>
</div>
<p id="xportxlsx" class="xport"><input type="submit" value="Export to XLSX!" onclick="doit('xlsx');"></p>


<script type="text/javascript">

function doit(type, fn, dl) {
    var elt = document.getElementById('data-table');
    var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
    return dl ?
        XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
        XLSX.writeFile(wb, fn || ('test.' + (type || 'xlsx')));
}


function tableau(pid, iid, fmt, ofile) {
    if(typeof Downloadify !== 'undefined') Downloadify.create(pid,{
            swf: 'downloadify.swf',
            downloadImage: 'download.png',
            width: 100,
            height: 30,
            filename: ofile, data: function() { return doit(fmt, ofile, true); },
            transparent: false,
            append: false,
            dataType: 'base64',
            onComplete: function(){ alert('Your File Has Been Saved!'); },
            onCancel: function(){ alert('You have cancelled the saving of this file.'); },
            onError: function(){ alert('You must put something in the File Contents or there will be nothing to save!'); }
    });
}
tableau('xlsxbtn',  'xportxlsx',  'xlsx',  'test.xlsx');

</script>

Old answer : You can use a workaround if sheetjs doesn't work. Datatable tool for instance has a plugin for exporting an HTML table to Excel. Demo : https://datatables.net/extensions/buttons/examples/initialisation/export.html

You could load Datatable in a hidden div for instance, and then your button "myBtn" launches the Export thanks to Excel Datatable export button

查看更多
登录 后发表回答