Exported HTML table to excel giving warning while opening the file using office Excel

Viewed 699

I am trying to export HTML table to xls format. But when I try to open the file using Excel, I am given a warning message. The waring message: enter image description here

I using this lines of code:

var file = new Blob([ html.outerHTML], {
            type: "application/vnd.ms-excel"
        });
        var url = URL.createObjectURL(file);
        var filename = dateSelected + "-" + "attendance" + ".xls"

        //here we are creating HTML <a> Tag which can be trigger to download the excel file.
        var a = document.createElement('a');
        a.id = "export";
        document.body.appendChild(a);
        //here we are checking if the bwoswer is IE or not if IE then we use window.navigator.msSaveBlob function otherwise Go with Simple Blob file.
        if (window.navigator && window.navigator.msSaveBlob) {
            window.navigator.msSaveBlob(file, filename);
            a.click();
            document.body.removeChild(a);
            document.body.removeChild(html);
        } else {
            a.download = filename;
            a.href = url;
            a.click();
            document.body.removeChild(a);
            document.body.removeChild(html);
        }

I tried to change the blob type but nothing is working. How can i solve this issue?

1 Answers

The Problem

If you open the file in notepad or other text editor, you will find that what is saved in the file is html or xml. However, open any XLS file generated by Excel, and you will see unreadable binary characters.

Since Excel can open xml files, you don't feel that there's something wrong under the hood. However the *.xls format is binary in nature and is different from xml. Excel would warn you if the file extension doesn't match the underlying file format. Google for excel extension hardening and you would know what I'm talking about.

The Solution

You need to save it in that (excel binary) format if you want excel to recognize it as XLS file. There are so many libraries available (some paid and some free) that can help you generate true XLS files. I would recommend you using one of those. The other way is to switch to another format like XLSX. The problem would remain same though. Unless excel is able to match the file extension with the file format, it will continue to show this warning. This is a security measure.

AFAIK there's probably a registry hack to get around this problem. But I won't recommend you that, because it will open you to the security problem for which this feature is there in Excel.

Related