Vue前端實(shí)現(xiàn)導(dǎo)出頁面為word的兩種方法
將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)會被解析為標(biāo)簽
以下是需要導(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)容某一行中有幾個(gè)字,那這幾個(gè)字就會兩端對齊,格式就錯(cuò)亂了
// 考慮到是因?yàn)?lt;br>標(biāo)簽才會兩端對齊,所以做如下的操作(去除<br>標(biāo)簽[br標(biāo)簽是換行標(biāo)簽],把內(nèi)容加到<div>標(biāo)簽內(nèi))
const regex = /([^>]*?)<br.*?>/gi; // 找到結(jié)束標(biāo)簽 ‘ <br /> ' 和開始標(biāo)簽 ‘ > ' 中間的內(nèi)容,把這部分內(nèi)容放到div標(biāo)簽內(nèi)
htmlString = htmlString.replace(regex, (match, p1) => { // p1就是找到的br標(biāo)簽中間的內(nèi)容
let ret = ''
if (p1.trim()){
ret += `<div>${p1}</div>` // 把找到的內(nèi)容放到div標(biāo)簽內(nèi)
} else {
ret += `<div> </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>標(biāo)簽,內(nèi)容加到<div>標(biāo)簽內(nèi)
const brs = htmlContent.querySelectorAll('br')
brs.forEach(br => {
const parent = br.parentNode //獲取父節(jié)點(diǎn)
let textNode = br.previousSibling //前一個(gè)兄弟節(jié)點(diǎn)
// while (textNode && textNode.nodeType !== Node.TEXT_NODE) {
// textNode = textNode.previousSibling; //循環(huán)查找,直到找到一個(gè)文本節(jié)點(diǎn)或沒有更多的兄弟節(jié)點(diǎn)
// }
if (textNode && textNode.nodeType === Node.TEXT_NODE && textNode.textContent.trim()){ //找到文本節(jié)點(diǎn),并且內(nèi)容不為空
const div = document.createElement('div')
div.textContent = textNode.textContent
parent.insertBefore(div, br)
parent.removeChild(textNode) //移除原有的文本節(jié)點(diǎn),避免內(nèi)容重復(fù)
} else {
const div = document.createElement('div')
div.innerHTML = ' '
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`)
})
},
注意:在當(dāng)前頁面引入依賴
import FileSaver from "file-saver"; import htmlDocx from "html-docx-js/dist/html-docx";**
問題:用此方法,最近遇到了一個(gè)問題,就是導(dǎo)出內(nèi)容很少的情況,比如:導(dǎo)出內(nèi)容只有一行或者兩行、三行,并且每行只有幾個(gè)字的情況,導(dǎo)出內(nèi)容就成亂碼了。如果有遇到此種情況并且有解決方案的大佬,感謝評論區(qū)分享。
第二種方法(需要使用jquery)
第一步:安裝所需依賴
npm install jquery --save npm install file-saver
第二步:創(chuàng)建兩個(gè)js文件
一個(gè)是jquery文件(jq.js),一個(gè)是插件js的文件(jquery.wordexport.js),我把這兩個(gè)js文件都放到utils文件夾下,注意:使用的時(shí)候一定要注意引用路徑。這兩個(gè)js文件代碼我都放到文章最后(有一個(gè)插件沒有依賴包,所以需要自己創(chuàng)建一個(gè)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)出的時(shí)候出現(xiàn)bug,大多是因?yàn)槲募窂揭胗袉栴},再次排查路徑引入
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前端實(shí)現(xiàn)導(dǎo)出頁面為word的兩種方法的詳細(xì)內(nèi)容,更多關(guān)于Vue頁面導(dǎo)出為word的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue項(xiàng)目中使用rem,在入口文件添加內(nèi)容操作
這篇文章主要介紹了vue項(xiàng)目中使用rem,在入口文件添加內(nèi)容操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

