我使用了以下代码。我可以下载扩展名为 .xls 的文件。当我打开此下载的文件时,我收到此警告:
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代码:
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.ms-excel;" });
saveAs(blob, "Statement.xls");`
HTML 代码:
`<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>`
外部库:
https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js
最佳答案
Office 和 Excel 能够处理两种不同的文件格式。由于这些格式从内部来看完全不同(旧格式是二进制的,新格式只是压缩的 XML),因此为这些格式分配了不同的扩展名和 mimetype。 显然,您正在使用新格式创建一个文件,并为其指定旧扩展名。 Excel 对此有所提示。
将代码更改为如下所示:
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
saveAs(blob, "Statement.xlsx");
为了学习,您可能需要使用十六进制编辑器查看您创建的文件。 其他人也有类似的问题,请看这里:https://github.com/eligrey/FileSaver.js/issues/139
关于javascript - 打开从 html 表导出的 xls 文件时出现警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33909511/