近日开发中需要将数据导成word文档,由于之前没玩过,饶了一圈,放弃了后端导出的方式,改由前端去生成。
1、需要引入两个js,jquery.wordexport.js,FileSaver.js。(当然,JQuery也需要优先引入)
傻瓜式操作,假设有div如下(要写行内样式):
<div id="applyContent" >
<div class="header">
<h4 style="text-align: center;">深圳******</h4>
</div>
<div class="content">
吧啦吧啦
</div>
<div class="footer">
</div>
</div>
触发导出或生成事件,js:
$("#applyContent").wordExport(fileName);
fileName改为你想要导出的文件名,无需加doc后缀。此时导出打开,发现不对劲,文件是Web版式视图,宽度太大,样式全崩了?
江湖救急:
进入jquery.wordexport.js ,看到以下内容:
top行最后原本是:
<!DOCTYPE html>\n<html>\n_html_</html>
修改为
<!DOCTYPE html>\n<html xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n_html_</html>
head行:
<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n
在<head>后插入
<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View></w:WordDocument></xml><![endif]-->
修改后代码块:
mhtml: {
top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n_html_</html>",
head: "<head><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View></w:WordDocument></xml><![endif]-->\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
body: "<body>_body_</body>"
}
此时再进行导出,发现已经是正常的页面视图。