3

I recently stumbled upon this JSFiddle about how to convert a table to Excel file directly without any fancy plugins. It really suits my need, but it has a flaw, I can't rename its file. Chrome renames the file to download and Firefox gives a random name to it.

$("#btnExport").click(function (e) {
    window.title = "filename.xls"; // this part doesn't work
    window.open('data:application/vnd.ms-excel,' +     
    $('#dvData').html());
    e.preventDefault();
});

How can I rename the downloaded file ?

DennyHiu
  • 4,861
  • 8
  • 48
  • 80

1 Answers1

2

Use <a> element with download attribute

let file = new Blob([$('#dvData').html()], {type:"application/vnd.ms-excel"});

let url = URL.createObjectURL(file);

let a = $("<a />", {
  href: url,
  download: "filename.xlsx"
})
.appendTo("body")
.get(0)
.click();

jsfiddle https://jsfiddle.net/jWAJ7/4549/

guest271314
  • 1
  • 15
  • 104
  • 177