Rename when exporting XLS

Asked

Viewed 156 times

0

Guys, I have a table and when I export it to xls, it automatically goes with the download name.xls , has to edit the name of the file before downloading?

to using 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 wanted to change the name using only basic JS.

1 answer

1


Here a solution can have a simpler way of doing.

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.