簡體   English   中英

使用 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);
        }

然而,有一個問題。 每當我嘗試打開它時,它都會顯示以下錯誤消息:

文件已損壞,無法打開。

(對不起,我無法嵌入圖像;我還沒有足夠的聲望)
所以,我有一種感覺,問題是我需要以不同的方式格式化我的文本,因為現在我只是像這樣調用函數: 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並且一切正常:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM