简体   繁体   中英

Warning when opening xls file which is exported from html table

I used the following code. I can download the file with extension .xls. When I open this downloaded file I receive this warning:

The file you are trying to open, 'Statement.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

Javascript Code:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.ms-excel;" });
saveAs(blob, "Statement.xls");`

HTML code:

`<table id="exportable">
   <tbody>
    <tr><th>ColumnOne</th><th>ColumnTwo</th><th>ColumnThree</th></tr>
    <tr><td>row1Col1</td><td>row1Col2</td><td>row1Col3</td></tr>
    <tr><td>row2Col1</td><td>row2Col2</td><td>row2Col3</td></tr>
    <tr><td>row3Col1</td><td>row3Col2</td><td>test</td></tr>
  </tbody>
</table>`

External library:

https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js

Office and Excel are able to cope with two different file formats. As those formats are totally different from the inside (the old one is binary, the new one is simply zipped up XML) different extensions and mimetypes were assigned to these formats. Obviously you are creating a file with the new format and assign it the old extension. Excel complains about that.

Change your code to look like this:

var blob = new Blob([document.getElementById('exportable').innerHTML], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
saveAs(blob, "Statement.xlsx");

For the sake of learning you might want to have a look at your created file with a hex editor. Others had similar issues, have a look here: https://github.com/eligrey/FileSaver.js/issues/139

When saving file with *.xls extension, file type should be set to "application/xls"

Since file type and extension will be matching, you shouldn't get any warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM