我正在尝试将HTML表导出为xls格式。但是当我试图使用Excel打开文件时,我会收到一条警告信息。呼啸的信息:
我使用这一行代码:
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);
}
我试图改变blob类型,但没有任何效果。我怎样才能解决这个问题?
发布于 2021-03-14 23:44:39
问题
如果您在记事本或其他文本编辑器中打开该文件,您将发现文件中保存的是html或xml。但是,打开Excel生成的任何XLS文件,您将看到不可读的二进制字符。
因为Excel可以打开xml文件,所以您不会觉得下面有什么问题。然而,*.xls格式本质上是二进制的,与xml不同。如果文件扩展名与基础文件格式不匹配,Excel将警告您。谷歌的excel extension hardening
,你就会知道我在说什么。
解决方案
如果要让excel识别为XLS文件,则需要将其保存为(excel二进制)格式。有那么多可用的库(有些是付费的,有些是免费的),它们可以帮助您生成真正的XLS文件。我建议你使用其中之一。另一种方法是切换到另一种格式,如XLSX。尽管如此,问题依然存在。除非excel能够将文件扩展名与文件格式匹配,否则它将继续显示此警告。这是一项安全措施。
AFAIK可能有一个注册表黑客来解决这个问题。但我不推荐您这样做,因为它会让您了解Excel中存在此特性的安全问题。
https://stackoverflow.com/questions/66542643
复制相似问题