1、加入两个外部js

  1)FileSaver.js

/*FileSaver.js* A saveAs() FileSaver implementation.* 1.3.2* 2016-06-16 18:25:19** By Eli Grey, http://eligrey.com* License: MIT*   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md*//*global self*/
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true*//*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js*/var saveAs = saveAs || (function(view) {"use strict";//IE <10 is explicitly unsupportedif (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {return;}vardoc=view.document//only get URL when necessary in case Blob.js hasn't overridden it yet, get_URL = function() {return view.URL || view.webkitURL ||view;}, save_link= doc.createElementNS("http://www.w3.org/1999/xhtml", "a"), can_use_save_link= "download" insave_link, click= function(node) {var event = new MouseEvent("click");node.dispatchEvent(event);}, is_safari= /constructor/i.test(view.HTMLElement), is_chrome_ios=/CriOS\/[\d]+/.test(navigator.userAgent), throw_outside= function(ex) {(view.setImmediate|| view.setTimeout)(function() {throwex;},0);}, force_saveable_type= "application/octet-stream"//the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to, arbitrary_revoke_timeout = 1000 * 40 //in ms, revoke = function(file) {var revoker = function() {if (typeof file === "string") { //file is an object URL
get_URL().revokeObjectURL(file);}else { //file is a File
file.remove();}};setTimeout(revoker, arbitrary_revoke_timeout);}, dispatch= function(filesaver, event_types, event) {event_types=[].concat(event_types);var i =event_types.length;while (i--) {var listener = filesaver["on" +event_types[i]];if (typeof listener === "function") {try{listener.call(filesaver, event||filesaver);}catch(ex) {throw_outside(ex);}}}}, auto_bom= function(blob) {//prepend BOM for UTF-8 XML and text/* types (including HTML)//note: your browser will automatically convert UTF-16 U+FEFF to EF BB BFif (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});}returnblob;}, FileSaver= function(blob, name, no_auto_bom) {if (!no_auto_bom) {blob=auto_bom(blob);}//First try a.download, then web filesystem, then object URLsvarfilesaver= this, type=blob.type, force= type ===force_saveable_type, object_url, dispatch_all= function() {dispatch(filesaver,"writestart progress write writeend".split(" "));}//on any filesys errors revert to saving with object URLs, fs_error = function() {if ((is_chrome_ios || (force && is_safari)) &&view.FileReader) {//Safari doesn't allow downloading of blob urlsvar reader = newFileReader();reader.onloadend= function() {var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');var popup = view.open(url, '_blank');if(!popup) view.location.href =url;url=undefined; //release reference before dispatchingfilesaver.readyState =filesaver.DONE;dispatch_all();};reader.readAsDataURL(blob);filesaver.readyState=filesaver.INIT;return;}//don't create more object URLs than neededif (!object_url) {object_url=get_URL().createObjectURL(blob);}if(force) {view.location.href=object_url;}else{var opened = view.open(object_url, "_blank");if (!opened) {//Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.htmlview.location.href =object_url;}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url);};filesaver.readyState=filesaver.INIT;if(can_use_save_link) {object_url=get_URL().createObjectURL(blob);setTimeout(function() {save_link.href=object_url;save_link.download=name;click(save_link);dispatch_all();revoke(object_url);filesaver.readyState=filesaver.DONE;});return;}fs_error();}, FS_proto=FileSaver.prototype, saveAs= function(blob, name, no_auto_bom) {return new FileSaver(blob, name || blob.name || "download", no_auto_bom);};//IE 10+ (native saveAs)if (typeof navigator !== "undefined" &&navigator.msSaveOrOpenBlob) {return function(blob, name, no_auto_bom) {name= name || blob.name || "download";if (!no_auto_bom) {blob=auto_bom(blob);}returnnavigator.msSaveOrOpenBlob(blob, name);};}FS_proto.abort= function(){};FS_proto.readyState= FS_proto.INIT = 0;FS_proto.WRITING= 1;FS_proto.DONE= 2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;returnsaveAs;
}(typeof self !== "undefined" &&self|| typeof window !== "undefined" &&window|| this.content
));//`self` is undefined in Firefox for Android content script context//while `this` is nsIContentFrameMessageManager//with an attribute `content` that corresponds to the windowif (typeof module !== "undefined" &&module.exports) {module.exports.saveAs=saveAs;
}else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {define([],function() {returnsaveAs;});
}

  2)jquery.wordexport.js

if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {(function($) {$.fn.wordExport= function(fileName) {fileName= typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";var static ={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>\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",body:"<body>_body_</body>"}};var options ={maxWidth:624};//Clone selected element before manipulating itvar markup = $(this).clone();//Remove hidden elements from the outputmarkup.each(function() {var self = $(this);if (self.is(':hidden'))self.remove();});//Embed all images using Data URLsvar images =Array();var img = markup.find('img');for (var i = 0; i < img.length; i++) {//Calculate dimensions of output imagevar w =Math.min(img[i].width, options.maxWidth);var h = img[i].height * (w /img[i].width);//Create canvas for converting image to data URLvar canvas = document.createElement("CANVAS");canvas.width=w;canvas.height=h;//Draw image to canvasvar context = canvas.getContext('2d');context.drawImage(img[i],0, 0, w, h);//Get data URL encoding of imagevar uri = canvas.toDataURL("image/png");$(img[i]).attr("src", img[i].src);img[i].width=w;img[i].height=h;//Save encoded image to arrayimages[i] ={type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),location: $(img[i]).attr("src"),data: uri.substring(uri.indexOf(",") + 1)};}//Prepare bottom of mhtml file with image datavar mhtmlBottom = "\n";for (var i = 0; i < images.length; i++) {mhtmlBottom+= "--NEXT.ITEM-BOUNDARY\n";mhtmlBottom+= "Content-Location: " + images[i].location + "\n";mhtmlBottom+= "Content-Type: " + images[i].type + "\n";mhtmlBottom+= "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";mhtmlBottom+= images[i].data + "\n\n";}mhtmlBottom+= "--NEXT.ITEM-BOUNDARY--";//TODO: load css from included stylesheetvar styles = "";//Aggregate parts of the file togethervar fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) +mhtmlBottom;//Create a Blob with the file contentsvar blob = newBlob([fileContent], {type:"application/msword;charset=utf-8"});saveAs(blob, fileName+ ".doc");};})(jQuery);
}else{if (typeof jQuery === "undefined") {console.error("jQuery Word Export: missing dependency (jQuery)");}if (typeof saveAs === "undefined") {console.error("jQuery Word Export: missing dependency (FileSaver.js)");}
}

2、在页面加入一个div或者在body上面加入一个id,div和body必须包含要导出的部分  

<divid="export_word"><p>要导出的页面内容</p>
</div>

3、可以指定id内容导出(按钮名称exportWord())

functionexportWord(){$("#export_word").wordExport();
}

4、也可以在自己的js里面写入(具体按钮自己写入方法名称exportWord(),按钮的id="export_word")

functionexportWord(){$("#export_word").hide();$("html").wordExport();$("#export_word").show();
}

转载于:https://www.cnblogs.com/ll409546297/p/6634776.html

html页面导出word文档相关推荐

  1. vue页面导出Word文档(含图片)

    引用插件 安装 npm i docxtemplater@3.17.6 npm i pizzip npm i jszip-utils@0.1.0 npm i jszip@2.6.1 npm i file ...

  2. vue前端html页面导出word文件,Vue-纯前端导出word文档

    在项目中,我们可以借助后端返回文件流实现文件下载.如果前端有数据,也可以借助前端框架进行下载.本文将介绍如何在前端纯js实现word文档导出. 1. 组件介绍 要实现前端纯js导出word文档,我们需 ...

  3. word根据目录切块php,PHP导出Word文档如何自定义目录?

    PHP导出Word文档如何自定义目录? 2018-09-19 class word { function start() { ob_start(); } function save($path) { ...

  4. jQuery表格导出Excel文件以及网页内容导出Word文档

    前言: 我在这里给大家介绍一下我们能用代码实现的最简单的两种转换为Excel文件以及Word文档的方法. jQuery表格导出Excel文件 先来看看我们的层级划分: 如图所示: demo.css 代 ...

  5. 今天做了freemaker 导出word文档 的bug修复,解决 \n换行 问题

    结合Freemaker导出文件 public void exportSimpleWord() throws Exception{// 要填充的数据, 注意map的key要和word中${xxx}的xx ...

  6. 关于Jquery导出word文档

    通常情况下,我们在开发过程中会遇到,导出网页上的内容保存至word文档中,类似这样的需求.前人早已为我们中下树,我们只需要乘凉即可.百度 Jquery 导出文档插件!我们会看到好多 资源,随便找一个引 ...

  7. java 图片 word文档_【Java】用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  8. java freemarker word_Java 用Freemarker完美导出word文档(带图片)(示例代码)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  9. jquery实现HTML页面导入word文档

    jquery实现HTML页面导入word文档 FileSaver.js /* * FileSaver.js * A saveAs() FileSaver implementation. * * By ...

  10. html导出 word文档教程

    最近搞项目 需要用到导出word 文档,由于呢 他要显示word格式,我就 用word文档生成模板,现在 分享给大家. 这是我在网上找的 demo,按照 功能 不错大家可以看看 1.加入两个外部js ...

最新文章

  1. 收藏!最新大数据产业地图 十大生态金矿百大公司起底【附下载】
  2. 如何用PHP写商品折扣_秒杀抢购时的超发,你用php如何优化的
  3. react-native(五)生成App
  4. 博客园首页新随笔联系管理订阅 Linux下四款Web服务器压力测试工具(http_load、webbench、ab、siege)介绍
  5. 如何安装最新版本的 SAP ABAP Development Tool ( ADT ) 2021年度更新
  6. python linux编程与window编程_Python3如何在Windows和Linux上打包
  7. 7-3 银行排队问题之单队列多窗口服务 (25 分)
  8. 面试基础算法及编程 第三弹(树(二叉树)相关:主要考察指针相关的操作)
  9. Lync Server 2013企业版部署系列之三:CA准备
  10. 【java】Java8 BiConsumer函数式接口
  11. VI 编辑器保存命令
  12. Proteus —— 电路仿真软件
  13. 【论文泛读171】具有对抗性扰动的自监督对比学习,用于鲁棒的预训练语言模型
  14. iOS Swift 使用 CLLocationManager 定位
  15. 垃圾分类小程序,识别和站点查询,答题,用户后台管理集一体的小程序
  16. 在线与本地文件同步方案
  17. 树形结构模型Django-MPTT
  18. 关于修改手机绑定那些事!
  19. 一个解决MacBook Pro 突然连接无线不能上网 方案
  20. urllib库用POST请求模仿有道在线翻译

热门文章

  1. 4年计算机博士读下来的一些感触
  2. Bomb Game(翻译)
  3. HTTP协议简介和系统命令curl,AIP调用 (ELK中运用)
  4. itsm安装部署(Vmware)
  5. WRF users guide Chap5
  6. python爬虫requests库的使用及python正则表达式的使用
  7. python 使用百度搜索推广API,获取账户基本信息
  8. Spring Boot 中的 HttpClient 新贵 Retrofit !
  9. run npm fund for details
  10. 一篇文章教你搞懂日志采集利器 Filebeat