javascript - 将 <div> 中的内容导出为 .docx 文件

标签 javascript html export filesaver.js

我在将 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 文件的下载,但当我打开它时,我收到以下错误:

The Open XML file note.docx cannot be opened because there are problems with the contents or the file name might contain invalid characters (for example. /).

Details: The file is corrupt and cannot be opened.

为了图形目的:

enter image description here

文本区域是我要导出到 <div id="editor"></div> 下的 word 文档中的区域.

最佳答案

jsfiddle

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');

关于javascript - 将 <div> 中的内容导出为 .docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36575093/

相关文章:

javascript - 为什么在 JavaScript 的 Date 构造函数中月份参数的范围从 0 到 11?

javascript - 难以定位按键来完成操作

javascript - 如何触发 Javascript 函数并在 Web 浏览器中接收它?

html - 用 CSS 旋转行星

html - Css 查询不能使事情响应?

datatables - 使用 select 元素从数据表导出数据导出 select 元素中的每个选项

JavaScript 模块 : "export * as" in visual studio code

javascript - 选中 div 而不是其中的文本

javascript - 使用 jQuery 选择变量中的内容而不是当前 DOM 中的内容?

mysql - 使用 MySQL 控制台导出数据库语法错误