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></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>
|