使用 JavaScript 在 Word 文档中保存文本
Saving text in a Word Document using JavaScript
对于一个项目,我需要将一些文本保存到 word 文档中。我使用此功能执行此操作:
function saveText(text) {
var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
但是,有一个问题。每当我尝试打开它时,它都会显示此错误消息:
The file is corrupt and cannot be opened.
(对不起,我无法嵌入图片;我还没有足够的声誉)
所以,我觉得问题在于我需要以不同的方式格式化我的文本,因为现在我只是像这样调用函数:saveText("Test");
。在 rtf 文件中,它的开头确实有很多东西,所以我想也许 word 也需要这个。但是,我在互联网上看了很多,但找不到解决方案。感谢您花时间阅读(并可能回答)这篇文章 :D
function saveText(text) {
var data = new Blob([text], {type: 'application/msword'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
我只是将 application/vnd.openxmlformatsofficedocument.wordprocessingml.document
更改为 application/ms-word
并且一切正常:)
对于一个项目,我需要将一些文本保存到 word 文档中。我使用此功能执行此操作:
function saveText(text) {
var data = new Blob([text], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
但是,有一个问题。每当我尝试打开它时,它都会显示此错误消息:
The file is corrupt and cannot be opened.
(对不起,我无法嵌入图片;我还没有足够的声誉)
所以,我觉得问题在于我需要以不同的方式格式化我的文本,因为现在我只是像这样调用函数:saveText("Test");
。在 rtf 文件中,它的开头确实有很多东西,所以我想也许 word 也需要这个。但是,我在互联网上看了很多,但找不到解决方案。感谢您花时间阅读(并可能回答)这篇文章 :D
function saveText(text) {
var data = new Blob([text], {type: 'application/msword'});
var textFile = window.URL.createObjectURL(data);
if (document.getElementById('download') !== null) {
document.body.removeChild(document.getElementById('download'));
}
var a = document.createElement("a");
a.setAttribute("id", "download");
a.setAttribute("href", textFile);
a.setAttribute("download", "");
a.textContent = "Click here to download the test for the students";
document.body.appendChild(a);
}
我只是将 application/vnd.openxmlformatsofficedocument.wordprocessingml.document
更改为 application/ms-word
并且一切正常:)