Rename when exporting XLS

0

I have a table and when I export it to xls, it automatically goes under the name of download.xls, how can I edit the file name before downloading?

To use the following JS code to export the table:

    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"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><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))

  }
})()

I'm using the following in the HTML button:

<button id="button-02"  type="button"  onclick="tableToExcel('tblExport', 'W3C Example Table')">Exportar Excel</button>

NOTE: I would like to change the name using only basic JS.

    
asked by anonymous 26.11.2017 / 04:51

1 answer

1

Here's a solution, you can have a simpler way to do it.

let tableToExcel = (nome, tabela) => {
  let link = document.querySelector('#link-to-download');
  let conteudo = document.querySelector(tabela);
  let mimetype = 'application/vnd.ms-excel';
  link.href = window.URL.createObjectURL(new Blob([conteudo.outerHTML], {
    type: mimetype
  }));
  link.download = nome;
  link.click();
};
table {
  border: 1px solid #ccc;
}
table td {
  padding: 4px;
  text-transform: uppercase;
}
table tr:nth-child(2n+0) td {
  background: #e7e7e7;
}

button {
  background: #069;
  border: 0;
  color: #fff;
  cursor: pointer;
  padding: 8px 30px;
  text-transform: uppercase;
}
<table id="tblExport">
    <tbody>
      <tr>
        <td>teste</td>
        <td>teste</td>
        <td>teste</td>
      </tr>
      <tr>
        <td>teste</td>
        <td>teste</td>
        <td>teste</td>
      </tr>
      <tr>
        <td>teste</td>
        <td>teste</td>
        <td>teste</td>
      </tr>
      <tr>
        <td>teste</td>
        <td>teste</td>
        <td>teste</td>
      </tr>
      <tr>
        <td>teste</td>
        <td>teste</td>
        <td>teste</td>
      </tr>
    </tbody>
  </table>
  <p><button onclick="tableToExcel('Arquivo.xlsx', '#tblExport')">Exportar Excel</button></p>
<a id="link-to-download" style="display: none;"></a>
    
26.11.2017 / 05:21