我无法将div的内容导出到.docx文件中。我使用的是FileSaver.js,在这里可以找到:https://github.com/eligrey/FileSaver.js/。
我的JavaScript函数:
function exportNote(){
var blob = new Blob([document.getElementById('editor').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"
});
saveAs(blob, "note.docx");
}我得到一个似乎是word文件的下载文件,但打开它时,我会得到以下错误:
opened文件note.docx无法打开,因为内容有问题,或者文件名可能包含无效字符(例如。/)。 详细信息:文件已损坏,无法打开。
为图形目的:

文本区域是我试图导出到word文档中的区域,该文档位于<div id="editor"></div>下。
发布于 2016-04-12 14:22:18
Html
<div id="main">
this is content of div
</div>JavaScript
function downloadInnerHtml(filename, elId) {
var elHtml = document.getElementById(elId).innerHTML;
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:' + 'text/doc' + ';charset=utf-8,' + encodeURIComponent(elHtml));
link.click();
}
var fileName = 'tags.doc'; // You can use the .txt extension if you want
downloadInnerHtml(fileName, 'main');发布于 2016-04-13 13:35:34
在麻省理工学院许可下,使用github上的开源库解决这个问题还有另一个解决方案:https://github.com/evidenceprime/html-docx-js。
我的解决方案:
function exportNote(contentId){
var filename = 'note.html'
var htmlDoc = document.getElementById(contentId).innerHTML;
var converted = htmlDocx.asBlob(htmlDoc);
saveAs(converted, "notes.docx");
}发布于 2021-07-30 15:56:14
由于有人在评论中有问题,我在积极使用的东西上贴上了标签。我在这里粘贴的函数几乎逐字显示在这个站点上:https://www.codexworld.com/export-html-to-word-doc-docx-using-javascript/
所以要归功于他们。关键是将div的内容保存到一个文件中并不是一个适当的HTML文档,这会导致Word犹豫。它需要一个主体、HTML和一些xmlns属性。在进行实际保存之前,该函数将获取innerHtml并将其打包。
只需使用保存要保存的内容的元素的名称和文件名调用Export2Word():
Export2Word('divMyContent','MyFileNameWithoutExtension');
function Export2Word(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 content = document.getElementById(element).innerHTML;
var html = preHtml+content+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+'.docx':'document.docx';
// 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);
}https://stackoverflow.com/questions/36575093
复制相似问题