javascript - 将 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);
}
解决方案
尝试将 url 'data' 更改为application/vnd.openxmlformats-officedocument.wordprocessing
. 未经测试。
可能需要进行其他更改。谷歌“docx mime 类型”。
推荐阅读
- php - 错误:类 'MailchimpMarketing\ApiClient'
- azure-active-directory - Blazor WASM - AzureAD 身份验证 - HttpContext.User.Claims 是空的?
- java - 如何让用户能够通过使用扫描仪功能无限输入键盘来输入内容?
- python - 不同模块中的相同导入是否“堆叠”在内存中?
- r - 使用来自 Shiny 模块的数字输入值作为用户定义函数的输入,并使用该函数的输出作为另一个模块中的输入
- python - 如何使用 pytest 设备优雅地模拟一个类?
- terminal - 终端问题,MicroPythonREPL
- python - 使用 Pandas 使用 SQL Server 中的数据创建 CSV 文件
- c# - 如果 USING 语句在 program.cs 中,WinForms:EnableVisualStyles() 不起作用?
- python-3.x - 我可以根据与熊猫数据框中的日期时间索引列不同的列重新采样吗