I have an Angular2 application and now it was asked me to implement a basic table to excel export.
The function that I'm using works but I don't know how to set the filename of the generated excel.
This is the function:
tableToExcel(e,table, name) {
console.log(e);
let 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]-->
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
</head>
<body>
<table>{table}</table>
</body>
</html>',
base64 = function (s) {
return window.btoa(decodeURI(decodeURIComponent(s)))
},
format = function (s, c) {
return s.replace(/{(\w+)}/g,
function (m, p) { return c[p];
})
}
if (!table.nodeType)
table = document.getElementById(table)
var ctx = {
worksheet: name || 'Worksheet', table: table.innerHTML
}
//window.location.href = uri + base64(format(template, ctx))
console.log(uri + base64(format(template, ctx)));
window.open(uri + base64(format(template, ctx)), '_blank', 'top=0,left=0,height=100%,width=auto');
return false;
}
and this is the button:
<a type="button" href="#" (click)="tableToExcel($event,'testTable', 'W3C Example Table')" download="Schede.xlsx" class="btn btn-warning"> Excel </a>
In this moment I can download the file excel but the filename is completely random.
Thanks to support