0

I have a string in a Javascript file that I'd like to make an Excel spreadsheet out of. I use the following code:

var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(excel);
location.href = url;

where "excel" here is the string in question.

This works perfectly well; I can download the file and then open it as an Excel spreadsheet, and it's formatted correctly and everything. But when I open the file, I have to choose which program I want to open it with. Is there a way to make it so that I can open the file with Excel automatically, without having to choose from a list of programs?

anon
  • 35
  • 5
  • After the file is downloaded, the local computer will determine which program to use to open the file. Are you naming the file with a default Excel extension like .xlsx? Depending on the browser you are using, there may be settings that need to be adjusted there as well. – David Jun 05 '17 at 13:27
  • Yeah, naming the file with .xlsx is what I'm currently trying to do, but the best I've been able to manage is putting ".xlsx" at the end of the "url" variable. Of course, all this does is put ".xlsx" in the last cell of the spreadsheet instead of making it open as a spreadsheet automatically. Do you know how to give it the .xlsx extension properly? – anon Jun 05 '17 at 13:33
  • Adding it to the end of the file name should do the trick. This answer might be what you are looking for https://stackoverflow.com/questions/15354261/how-to-change-the-name-of-file-while-exporting-data-to-excel – David Jun 05 '17 at 13:55

1 Answers1

0

Alright, David's advice works. This link:

http://www.kubilayerdogan.net/javascript-export-html-table-to-excel-with-custom-file-name/

will take an HTML table and export it to an Excel spreadsheet. I was using a raw string instead of an HTML table, but the relevant part works the same for both:

var a = document.createElement("A");
var data_type = 'data:application/vnd.ms-excel';
a.href = data_type + "," + excel;
a.download = "student_data.xlsx";
a.click();

This will automatically download the string as a .xlsx file.

I did run into other issues with the .xlsx format - Excel thought the file was corrupt and wouldn't open it - but using .csv instead of .xlsx fixes that.

anon
  • 35
  • 5