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
  • 3,032
  • 5
  • 39
  • 63

2 Answers2

3

File names can be suggested through HTTP headers, but there's no standard mechanism accomplishing the same thing with data URIs or window.open.

There are some ways to specify a filename when downloading generated data, but AFAIK there aren't any that are supported in multiple browsers.

One of these ways is the new download attribute for <a> elements. For example:

Download Your Foo This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file.

Instead of using window.open() you could generate an invisible link with the download attribute and .click() it.

var str = "Name, Price\nApple, 2\nOrange, 3";
var uri = 'data:text/csv;charset=utf-8,' + str;

var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "data.csv";

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
Bhupinder kumar
  • 760
  • 5
  • 19
1

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
  • 12
  • 91
  • 170