vue前端实现导出页面为word(两种方法)

这篇具有很好参考价值的文章主要介绍了vue前端实现导出页面为word(两种方法)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

将vue页面导出为word文档,不用写模板,直接导出即可。

第一种方法(简单版)

第一步:安装所需依赖

npm install html-docx-js -S
npm install file-saver -S

第二步:创建容器,页面使用方法

前端vue导出页面,前端,vue.js,word,js,javascript

注意:在当前页面引入依赖

import FileSaver from "file-saver"; 
import htmlDocx from "html-docx-js/dist/html-docx";**

第二种方法(需要使用jquery)

第一步:安装所需依赖

npm install jquery --save
npm install file-saver

第二步:创建两个js文件,一个是jquery文件(jq.js),一个是插件js的文件(jquery.wordexport.js),我把这两个js文件都放到utils文件夹下,注意:使用的时候一定要注意引用路径。这两个js文件代码我都放到文章最后(有一个插件没有依赖包,所以需要自己创建一个js文件(jquery.wordexport.js))

第三步:在需要导出的页面引入文件

import $ from "@/utils/jq"; // 文件引入路径一定要正确,这是第二步创建的js文件(jq.js)
import saveAs from "file-saver/dist/FileSaver";
import "@/utils/jquery.wordexport"; // 文件引入路径一定要正确,这是第二步创建的js文件(jquery.wordexport.js)

第三步:页面使用方法

前端vue导出页面,前端,vue.js,word,js,javascript

注意:如果导出的时候出现bug,大多是因为文件路径引入有问题,再次排查路径引入文章来源地址https://www.toymoban.com/news/detail-857484.html

jq.js

import $ from "jquery";
  window.$ = $;
  window.jQuery = $;
export default $;

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 xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">\n_html_</html>',
                  head:
                    '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]--></head>\n',
                  body: "<body>_body_</body>",
              },
          };
          var options = {
              maxWidth: 624,//最大宽度
          };
          // Clone selected element before manipulating it
          var markup = $(this).clone();

          // Remove hidden elements from the output
          markup.each(function () {
              var self = $(this);
              if (self.is(':hidden'))
                  self.remove();
          });

          // Embed all images using Data URLs
          var images = Array();
          var img = markup.find('img');
          // var img = new Image(); 用这一行的话,WPS不显示图片,用上面的——只兼容office Word。
          var mhtmlBottom = "\n";
          for (var i = 0; i < img.length; i++) {
              // Calculate dimensions of output image
              var w = Math.min(img[i].width == 0 ? options.maxWidth : img[i].width, options.maxWidth);
              var h = (img[i].height == 0 ? options.defaultLength : img[i].height) * (w / (img[i].width == 0 ? options.maxWidth : img[i].width));

              // Create canvas for converting image to data URL
              var canvas = document.createElement("CANVAS");
              canvas.width = w;
              canvas.height = h;
              // Draw image to canvas
              var context = canvas.getContext('2d');
              context.drawImage(img[i], 0, 0, w, h);
              // Get data URL encoding of image
              var uri = canvas.toDataURL("image/png");
              // console.log(i+":"+uri);
              $(img[i]).attr("src", img[i].src);
              img[i].width = w;
              img[i].height = h;

              mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
              mhtmlBottom += "Content-Location: " + uri + "\n";
              mhtmlBottom += "Content-Type: " + uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")) + "\n";
              mhtmlBottom += "Content-Transfer-Encoding: " + uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")) + "\n\n";
              mhtmlBottom += uri.substring(uri.indexOf(",") + 1) + "\n\n";
          }

          mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";

          //TODO: load css from included stylesheet
          var styles = "";

          // Aggregate parts of the file together
          var 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 contents
          var blob = new Blob([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)");
  }
}

到了这里,关于vue前端实现导出页面为word(两种方法)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Html转PDF,前端JS实现Html页面导出PDF(html2canvas+jspdf)

    一、背景介绍 ​ 当我们在不想改变后端代码的同时想是纯html页面导出PDF,那么(html2canvas+jspdf)就是无疑最好的选择,导出时它不占用我们服务器的资源,而是由用户本地自行执行js文件下载PDF,不占用我们系统的带宽,所以这无非是最好的选择方式。 二、疑问 1、为什么要

    2024年01月23日
    浏览(43)
  • Vue中前端导出word文件

    很多时候在工作中会碰到完全由前端导出word文件的需求,因此特地记录一下比较常用的几种方式。 一、提供一个word模板 该方法提供一个word模板文件,数据通过参数替换的方式传入word文件中,灵活性较差,适用于简单的文件导出。需要依赖: docxtemplater、file-saver、jszip-uti

    2024年02月05日
    浏览(34)
  • 前端刷新页面的五种方法(含原生js、vue和react)

    1、window.history.go(0)方法 2、location.reload()方法 3、location.href=location.href方法 4、vue-router方法 5、react-router方法

    2024年02月16日
    浏览(38)
  • 记录--Vue中前端导出word文件

    很多时候在工作中会碰到完全由前端导出word文件的需求,因此特地记录一下比较常用的几种方式。 该方法提供一个word模板文件,数据通过参数替换的方式传入word文件中,灵活性较差,适用于简单的文件导出。需要依赖: docxtemplater、file-saver、jszip-utils、pizzip 。   调用down

    2024年02月08日
    浏览(26)
  • vue element ui 导出word文件方法

    1首先安装导出word需要的依赖 -- 安装 docxtemplater npm install docxtemplater pizzip  --save   -- 安装 jszip-utils npm install jszip-utils --save   -- 安装 jszip npm install jszip --save   -- 安装 FileSaver npm install file-saver --save 2.然后在需要导入的页面引入 import docxtemplater from \\\'docxtemplater\\\' import PizZip from \\\'p

    2024年02月10日
    浏览(25)
  • vue 前端导出页面图表保存为Html格式文档

    问题描述: 图一 解决思路: 想要达到要求的效果,网上找了很久,最后记录下2种方案: 方案一、使用html2canvas组件,html2canvas的作用就是允许我们直接在用户浏览器上拍摄网页或某一部分的截图。它的屏幕截图是基于DOM元素的,实际上它不会生成实际的屏幕截图,而是基于

    2024年02月03日
    浏览(30)
  • Vue3——html-doc-ja(html导出为word的js库)

    官方地址  html-doc-js - npm 在 exportWord 方法执行时,将页面中mjx-assistive-mml 节点清除即可,如下图所示

    2024年04月14日
    浏览(29)
  • vue实现导出excel的两种方式

    通过vue实现导出有两种方式: (1)后端返回的是一个地址,直接拼接打开下载就行 (2)后端返回的是文件流的形式,这个时候就需要在请求头还有返回值的地方设置一下 (1)设置请求头 (2)设置返回结果,处理返回我文件流 (3)附加说明 有的时候做到上述几步还是不

    2024年02月12日
    浏览(33)
  • 若依vue 多table前端HTML页面导出一张Excel表

    导入依赖,具体前端vue配置就不介绍了,直接晒具体细节代码 js代码 点个赞吧!

    2024年02月15日
    浏览(44)
  • 前端html-docx实现html转word,预览并导出文件

    使用工具:html-docx 优势:图片、图表能直接预览并转为base64导出,省去后端难以实现图表的生成后插入的麻烦 劣势:适合一些简单的word模板导出(比如只有标题正文简单的表格图表图片的文档),复杂的可以直接忽略。比如:纸张大小、纸张方向、css大部分样式等等(经本

    2024年02月16日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包