-->

phpsreadsheet create excel from html table

2019-08-17 08:28发布

问题:

There is no documentation for using phpspreadsheet to form an excel file from a html table.

This is possible using "jquery.table2excel.js" but it seems pretty old; makes old excel files and makes warnings about the file.

phpspreadsheet makes a good excel file, but I just can't find any answers to do the function.

回答1:

Use the HTML Reader to read the data into a Spreadsheet, then the appropriate writer (xls or xlsx)



回答2:

You can use sheetJS library to convert custom html table to xslx.

Working Code sample :

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