首页 > 解决方案 > 将 HTML 导出到 Word

问题描述

我需要将一些 HTML 导出到 Word 并遇到此链接: https ://www.codexworld.com/export-html-to-word-doc-docx-using-javascript

代码如下。它会生成一个 .doc 文件(旧的 Word 格式),但我更喜欢 .docx。文章说可以通过少量修改来完成,但没有说明如何。有谁知道如何进行此更改?

function Export2Doc(element, filename = ''){
    var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
    var postHtml = "</body></html>";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });
    
    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
    
    // Specify file name
    filename = filename?filename+'.doc':'document.doc';
    
    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;
        
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
    
    document.body.removeChild(downloadLink);
}

标签: javascripthtmlms-wordexport

解决方案


尝试将 url 'data' 更改为application/vnd.openxmlformats-officedocument.wordprocessing. 未经测试。

可能需要进行其他更改。谷歌“docx mime 类型”。


推荐阅读