0

Galera, tenho uma tabela e quando exporto ela pra xls, automaticamente vai com o nome de download.xls , tem como editar o nome do arquivo antes de fazer o download?

to usando o seguinte código JS pra exportar a tabela:

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

  }
})()

E to usando o seguinte no botão HTML :

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

OBS: Queria mudar o nome usando apenas JS básico.

1 Resposta 1

1

Aqui uma solução, pode ter uma maneira mais simples de se fazer.

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>

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .