使用JavaScript在Word文档中保存文本

时间:2018-10-21 18:12:48

标签: javascript html ms-word blob docx

对于一个项目,我需要将一些文本保存到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);
        }

但是,有一个问题。每当我尝试打开它时,它都会显示以下错误消息:

  

该文件已损坏,无法打开。

(对不起,我无法嵌入图片;我的信誉还不够高)
因此,我觉得问题是我需要以不同的方式设置文本格式,因为现在我只是像这样调用函数:saveText("Test");。在rtf文件中,一开始确实有很多东西,所以我想也许单词也需要这个。但是,我在互联网上看了很多,找不到解决方案。感谢您抽出宝贵的时间阅读(也许回答)此:D

2 个答案:

答案 0 :(得分:0)

问题在于docx格式不是像.txt这样的简单文本格式。

docx是一种格式,它是将多个XML文件压缩成一个文件。

例如,包含文本Hello World的段落将如下所示:

<w:p>
  <w:pPr>
    <w:pStyle w:val="Normal"/>
    <w:rPr/>
  </w:pPr>
  <w:r>
    <w:rPr/>
    <w:t>Hello World</w:t>
  </w:r>
</w:p>

您可以将任何.docx文件重命名为.zip,然后将其解压缩以查看文件的内容。

要做您想做的事,我建议您使用docxtemplater,它是一个javascript库,可以用任何值替换word文件中的文本。我是该库的创建者,可以直接在浏览器中很好地工作。

您可以在https://github.com/open-xml-templating/docxtemplater上找到该项目的github,并在https://docxtemplater.com/demo上找到一个演示

答案 1 :(得分:0)

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,一切正常:)