一、使用步骤
1.引入依赖包
代码如下(示例):
npm install file-saver --save
2.在下载页面导入
代码如下(示例):
import { saveAs } from 'file-saver'
3.在页面中可以定义一个html模板,也可以在全局写
getModelHtml(mhtml) {
return `<!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">
<head>
<!--[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]-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>${this.test}</title>
<style>${wordCss}</style>
</head>
<body>
<div style="display: flex;justify-content: center;">
${mhtml}
</div>
</body>
</html>`
},
注释:css可以重新定义一个后缀为.js的文件,并在使用以上模板的文件中引入
这边是css的书写方式
export const wordCss = `
.title {
height: 64px;
width: 800px;
text-align: center;
line-height: 64px;
font-size: 20px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 500;
color: rgba(0, 11, 46, 0.85);
}
.all-box {
position: relative;
}
.all-topic {
padding: 24px;
}
`
4.最后就是在点击下载事假中
const node = document.querySelector('.exportBox').innerHTML
const html = this.getModelHtml(node)
const blob = new Blob([html], { type: 'application/msword;charset=utf-8' })
saveAs(blob, this.test + '.doc')
注释:按着以上模板代码写就行,只是获取的don元素的话,每个人的定义名称不一样(做修改即可)
总结
下载下来的话,是正常的,但是要是页面上存在图片的话,(我这边是富文本框,是后端给我返回的,然后我是用公司同事分装的标签渲染的 v-html),然就后端给我的图片路劲是../(相对路劲),所以下载下来图片会丢失,要把图片改成绝对路劲。因为我的图片是后端返回的,所以我给返回数据的所有图片路劲进行了替换
const host = window.location.protocol + '//' + window.location.host
const data = JSON.stringify(infoData).replace(RegExp('../upload-file', 'g'),
`${host}/upload-file`)
this.infoData = JSON.parse(data)