avatar

Javascript 生成word文档

Javascript 生成word文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>word</title>
</head>
<body>
<button id="btn">下载</button>
<script>
const btn = document.getElementById('btn')
btn.onclick = function () {
// word文档内容, 可以使用img标签插入网络图片
const body = `<table><tr><td>序号</td><td>名称</td></tr><tr><td>1</td><td>AAAAAAAAAA</td></tr></table>`
// 设置默认打开时使用页面视图,缺少以下代码时打开可能默认打开使用web视图
const html = `<!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><style>.head {font-size: 28px;text-align: center;font-weight: 500;}table {width: 100%;border: 1px solid #a3a3a3;line-height: 2;font-size: 20px;font-weight: 400;border-collapse: collapse;}td {border: 1px solid #a3a3a3;padding: 0 10px;}.title {text-align: center;margin: 0 -10px;border-bottom: 1px solid #a3a3a3;}.items {display: flex;flex-wrap: wrap;}.item {width: calc(25% - 10px);box-sizing: border-box;margin: 5px;}</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></html>`
const blob = new Blob([html], { type: 'application/vnd.ms-word' })
const link = document.createElement('a')
link.download = 'attachment.docx'
link.href = URL.createObjectURL(blob)
link.click()
}
</script>
</body>
</html>
文章作者: pengweifu
文章链接: https://www.pengwf.com/2023/10/30/web/JS-word/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 麦子的博客
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论