Found code that saves data from a table in xls

< script type = "text/javascript" > var tableToExcel = (function() { var 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]--></head><body><table>{table}</table></body></html>', base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } window.location.href = uri + base64(format(template, ctx)) } })() < /script> 

Keeps everything all right. But there are two important questions:

1) When you save a file, it is saved as downloaded .xls files. How can I mark this name? I could not understand (

2) When opened in Excel, it gives such (but everything is well displayed) enter image description here

    1 answer 1

    1. Already discussed, look for solutions here: How to set the name of the downloaded file in JavaScript using data url

    2. Because the extension should be .xlsx (the XML-shaped format that you use), and not .xls (the binary format, which is long obsolete).

    It is necessary to replace one line:

    var uri = 'data:application/vnd.ms-excel;base64,',

    on:

    var uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,',

    By the way, here is the complete list of types for different office files: https://stackoverflow.com/questions/4212861/

    • The first one is fixed. And how to deal with the second one? How to make it happen? - DarkVss
    • Corrected your answer, look, mark as correct. - Sergey Snegirev
    • For fun, you can simply paste the text data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64, into the browser's line :) - Sergey Snegirev