欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue前端實現(xiàn)導(dǎo)出頁面為word的兩種方法

 更新時間:2024年12月11日 10:33:58   作者:m0_74823434  
這篇文章主要介紹了Vue前端實現(xiàn)導(dǎo)出頁面為word的兩種方法,文中通過代碼示例和圖文介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

將vue頁面導(dǎo)出為word文檔,不用寫模板,直接導(dǎo)出即可。

第一種方法(簡單版)

第一步:安裝所需依賴

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

第二步:創(chuàng)建容器,頁面使用方法

簡單版:導(dǎo)出內(nèi)容為純文字,沒有表格、圖片這些東西

第三步:創(chuàng)建容器,頁面使用方法

(復(fù)雜版:導(dǎo)出內(nèi)容帶有表格和圖片的情況 【使用了tinymce富文本編輯器會有表格和圖片,然后需要導(dǎo)出帶有表格和圖片的word文檔】)
注意:使用v-html更新元素的 innerHTML,html結(jié)構(gòu)會被解析為標簽
以下是需要導(dǎo)出的內(nèi)容(exportContent):

 <div 
    id="managerReport"
    class="checkInfoStyle">
    <div v-html="exportContent"></div>
 </div>

把exportContent 內(nèi)容導(dǎo)出為word文檔
下邊直接寫導(dǎo)出方法了:

    // 第一種方法
    wordDownload1 () {
      this.$nextTick(() => {
        const htmlContent = document.getElementById("managerReport") // managerReport id要對應(yīng)
        // 注意:直接導(dǎo)出表格沒有邊框并且不是100%撐滿的,所以需要做以下的處理
        // 查找并修改表格的樣式
        const tables = htmlContent.querySelectorAll('table');
        tables.forEach(table => {
          table.style.borderCollapse = 'collapse'
          table.style.width = '100%'

          table.querySelectorAll('td, th').forEach((cell, index) => {
            if (cell){
              cell.style.border = '1px solid black'
              cell.style.padding = '8px'
            }
          })
        })

		// 拿到需要導(dǎo)出的內(nèi)容
        let htmlString = htmlContent.innerHTML
        // 注意:以下操作是為了解決導(dǎo)出內(nèi)容為兩端對齊的情況,如果導(dǎo)出內(nèi)容某一行中有幾個字,那這幾個字就會兩端對齊,格式就錯亂了
        // 考慮到是因為<br>標簽才會兩端對齊,所以做如下的操作(去除<br>標簽[br標簽是換行標簽],把內(nèi)容加到<div>標簽內(nèi))
        const regex = /([^>]*?)<br.*?>/gi;  // 找到結(jié)束標簽 ‘ <br /> ' 和開始標簽 ‘ > ' 中間的內(nèi)容,把這部分內(nèi)容放到div標簽內(nèi)
        htmlString = htmlString.replace(regex, (match, p1) => { // p1就是找到的br標簽中間的內(nèi)容
          let ret = ''
          if (p1.trim()){
            ret += `<div>${p1}</div>` // 把找到的內(nèi)容放到div標簽內(nèi)
          } else {
            ret += `<div>&nbsp;</div>` // 不加此步驟,如果導(dǎo)出內(nèi)容中間有空行就會解析不了,直接吞掉空行了
          }
          return ret
        })
        // 將HTML轉(zhuǎn)換為Blob對象
        const blob = htmlDocx.asBlob(htmlString);
        saveAs(blob, `${this.editData.cTopicC}(${this.editData.dDate}).docx`)
      })
    },


   // 第二種方法
    wordDownload2 () {
      this.$nextTick(() => {
        const htmlContent = document.getElementById("managerReport")

        // 查找并修改表格的樣式
        const tables = htmlContent.querySelectorAll('table')
        tables.forEach(table => {
          table.style.borderCollapse = 'collapse'
          table.style.width = '100%'

          table.querySelectorAll('td, th').forEach((cell, index) => {
            if (cell){
              cell.style.border = '1px solid black'
              cell.style.padding = '8px'
            }
          })
        })

        //去除<br>標簽,內(nèi)容加到<div>標簽內(nèi)
        const brs = htmlContent.querySelectorAll('br')
        brs.forEach(br => {
          const parent = br.parentNode                  //獲取父節(jié)點
          let textNode = br.previousSibling             //前一個兄弟節(jié)點
          // while (textNode && textNode.nodeType !== Node.TEXT_NODE) {
          //   textNode = textNode.previousSibling;        //循環(huán)查找,直到找到一個文本節(jié)點或沒有更多的兄弟節(jié)點
          // }
          if (textNode && textNode.nodeType === Node.TEXT_NODE && textNode.textContent.trim()){ //找到文本節(jié)點,并且內(nèi)容不為空
            const div = document.createElement('div')
            div.textContent = textNode.textContent
            parent.insertBefore(div, br)

            parent.removeChild(textNode)                //移除原有的文本節(jié)點,避免內(nèi)容重復(fù)
          } else {
            const div = document.createElement('div')
            div.innerHTML = '&nbsp;'
            parent.insertBefore(div, br)
          }
          parent.removeChild(br)
        })

        const htmlContentCopy = htmlContent.cloneNode(true)

        const imgs = htmlContentCopy.querySelectorAll('img')
        imgs.forEach(img => {
          let docxWidth = 620
          if (img.width > docxWidth){
            img.height = img.height * docxWidth / img.width
            img.width = docxWidth
          }
        })

        // 將HTML轉(zhuǎn)換為Blob對象
        const blob = htmlDocx.asBlob(htmlContentCopy.innerHTML)
        saveAs(blob, `${this.editData.cTopicC}(${this.editData.dDate}).docx`)
      })
    },

注意:在當前頁面引入依賴

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

問題:用此方法,最近遇到了一個問題,就是導(dǎo)出內(nèi)容很少的情況,比如:導(dǎo)出內(nèi)容只有一行或者兩行、三行,并且每行只有幾個字的情況,導(dǎo)出內(nèi)容就成亂碼了。如果有遇到此種情況并且有解決方案的大佬,感謝評論區(qū)分享。

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

第一步:安裝所需依賴

npm install jquery --save
npm install file-saver

第二步:創(chuàng)建兩個js文件

一個是jquery文件(jq.js),一個是插件js的文件(jquery.wordexport.js),我把這兩個js文件都放到utils文件夾下,注意:使用的時候一定要注意引用路徑。這兩個js文件代碼我都放到文章最后(有一個插件沒有依賴包,所以需要自己創(chuàng)建一個js文件(jquery.wordexport.js))
第三步:在需要導(dǎo)出的頁面引入文件

第三步:在需要導(dǎo)出的頁面引入文件

import $ from "@/utils/jq"; // 文件引入路徑一定要正確,這是第二步創(chuàng)建的js文件(jq.js)
import saveAs from "file-saver/dist/FileSaver";
import "@/utils/jquery.wordexport"; // 文件引入路徑一定要正確,這是第二步創(chuàng)建的js文件(jquery.wordexport.js)

第四步:頁面使用方法

注意:如果導(dǎo)出的時候出現(xiàn)bug,大多是因為文件路徑引入有問題,再次排查路徑引入

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
Content-Base: " +
                    location.href +
                    '
Content-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"

--NEXT.ITEM-BOUNDARY
Content-Type: text/html; charset="utf-8"
Content-Location: ' +
                    location.href +
                    "

<!DOCTYPE html>
" +
                    '<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">
_html_</html>',
                  head:
                    '<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
_styles_
</style>
<!--[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>
',
                  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 = "
";
          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
";
              mhtmlBottom += "Content-Location: " + uri + "
";
              mhtmlBottom += "Content-Type: " + uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")) + "
";
              mhtmlBottom += "Content-Transfer-Encoding: " + uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")) + "

";
              mhtmlBottom += uri.substring(uri.indexOf(",") + 1) + "

";
          }

          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"); // 注意:不要改成docx,不然會打不開!?。?
          
      };
  })(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前端實現(xiàn)導(dǎo)出頁面為word的兩種方法的詳細內(nèi)容,更多關(guān)于Vue頁面導(dǎo)出為word的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • vue3實現(xiàn)多條件搜索功能的示例代碼

    vue3實現(xiàn)多條件搜索功能的示例代碼

    搜索功能在后臺管理頁面中非常常見,這篇文章就著重講一下vue3-admin-element框架中如何實現(xiàn)一個頂部多條件搜索功能,感興趣的小伙伴可以了解一下
    2023-08-08
  • vue項目中使用rem,在入口文件添加內(nèi)容操作

    vue項目中使用rem,在入口文件添加內(nèi)容操作

    這篇文章主要介紹了vue項目中使用rem,在入口文件添加內(nèi)容操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • vue-ajax小封裝實例

    vue-ajax小封裝實例

    下面小編就為大家?guī)硪黄獀ue-ajax小封裝實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • vue3使用flv.js播放推流視頻的示例代碼

    vue3使用flv.js播放推流視頻的示例代碼

    本文主要介紹了vue3使用flv.js播放推流視頻的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • 深入解析vue 源碼目錄及構(gòu)建過程分析

    深入解析vue 源碼目錄及構(gòu)建過程分析

    這篇文章主要介紹了vue 源碼目錄及構(gòu)建過程分析,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2019-04-04
  • vue使用npm發(fā)布自己的公網(wǎng)包

    vue使用npm發(fā)布自己的公網(wǎng)包

    本文主要介紹了vue使用npm發(fā)布自己的公網(wǎng)包,通過創(chuàng)建一個簡單的npm包,本文詳細闡述了從創(chuàng)建到發(fā)布的整個過程,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08
  • Vue中封裝input組件的實例詳解

    Vue中封裝input組件的實例詳解

    這篇文章主要介紹了Vue中封裝input組件的實例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下
    2017-10-10
  • vue引入外部的js文件的10種方法總結(jié)

    vue引入外部的js文件的10種方法總結(jié)

    這篇文章主要為大家詳細介紹了vue項目中引入外部的js文件的10種方法,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的小伙伴可以參考下
    2023-08-08
  • vue頁面使用多個定時器的方法

    vue頁面使用多個定時器的方法

    這篇文章主要為大家詳細介紹了vue頁面使用多個定時器的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-09-09
  • vue3子組件數(shù)據(jù)無法更新問題

    vue3子組件數(shù)據(jù)無法更新問題

    這篇文章主要介紹了vue3子組件數(shù)據(jù)無法更新問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10

最新評論