Eugene Sukh
Eugene Sukh

Reputation: 2727

Name file with datetime now (JS)

I have code to download HTML table like excel

Here is code

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"><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));
  }
})()
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Експортувати в Excel">

Now it's downloading like "download.xls", I need to name it with DateTime. How can I do this?

Upvotes: 3

Views: 3158

Answers (3)

NullPointer
NullPointer

Reputation: 7368

If you want to achieve it client side then HTML5 provides dowload attribute inside <a> tag

<a href="http://www.google.com/.." download="download.xls">download me</a>

JavaScript Solution

function setDownloadFileName() {
    var a = document.getElementById("dowloadFileID");
    a.setAttribute("download","FileName_" + new Date().getTime()+ ".xlsx");
}

document.getElementById("dowloadFileID").addEventListener("click", setDownloadFileName);
<a id="dowloadFileID" href="Link../" >Download</a>

Reference:

https://html.spec.whatwg.org/dev/links.html#downloading-resources

https://developers.google.com/web/updates/2011/08/Downloading-resources-in-HTML5-a-download

Upvotes: 1

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

how to download file using anchor tag <a>

set your URL as href to the anchor element and force an onClick() event to download the file with the name

example : <a href="/images/myw3schoolsimage.jpg" download="filename.xls">

<script>
var links = [....]
var _html = links.map(link => {
    return `<a href="${link}" download="${Date.now()}.xls">`
}).join();
body.innerHTML += `<div style="display:none;" class="downloadList">${_html}</div>`;
Array.from(document.querySelectorAll('.downloadList a')).map(anchor => anchor.click());

Clearly, there are a lot of optimizations to be done and it is a crude example. But should work

Upvotes: 1

Terry Wei
Terry Wei

Reputation: 1531

You should use <a> element with download attribute to determine the file's name.

Here is an example of how to dynamically create a <a> element and set src and download attibutes to download:

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"><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
    }
    
    // here's how to download with datetime file name.

    // DateTime filename
    var filename = new Date().getTime();
    
    var element = document.createElement('a');
    element.setAttribute('href', uri + base64(format(template, ctx)));
    element.setAttribute('download', filename);
    element.style.display = 'none';

    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }
})()

var table = document.getElementsByTagName('table')[0];
var newTableToExcel = new tableToExcel(table, 'myname');
<table>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

Upvotes: 2

Related Questions