Reputation: 57469
Is there a way to generate an .xslx file from javascript and allow the user to download it by javascript? This page is geared towards being run offline in html 5 with no internet connectivity.
Upvotes: 10
Views: 6756
Reputation: 22
**Yes You Can do it using javascript**
** call function expexcel('table_id','output_file_name');**
<script>
function expexcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
Upvotes: 1
Reputation: 18002
You can generate any Office document with OpenXML SDK for Javascript http://openxmlsdkjs.codeplex.com/
As for allowing the user to save a file from JS I recommend FileSaver.js https://github.com/eligrey/FileSaver.js/
Upvotes: 0
Reputation: 2538
As Javascript has no file I/O, it's not going to be easy for your users to download. However, this kind of work is perfectly suited for a simple PHP script, which could generate your XSLX and save to your server dynamically.
Upvotes: 0
Reputation: 20387
It has been done successfully by Ed Spencer. This project is using an EXT DataGrid as the source of the data, but I'm sure you could adapt it pretty easily.
Upvotes: 1
Reputation: 284927
You could generate a data URI, and let the user save the link. However, IE8 has very limited support for data URIs. There is a 32 KB limit, and it's not allowed to be used with a href
.
Also, you still need to find a actual XLSX JS library... But it is possible.
Upvotes: 1