前端时间遇到一个需求,需要将网页内容保存为word下载,当时实现了,前几天又在前端群遇到小伙伴问相同的问题,跟他分享了代码。觉得既然有人遇到了一样的需求,那我就干脆整理下一 记录和分享吧,其实有现成的插件叫fileSave.js 但是是依赖JQuery的,像我这种人能不不加依赖就不加依赖,能自己写就自己写的脾气,当然是自己写了,其实也不复杂直接上代码吧。具体实现方法:
const exportWord = () => {
//gigi 原生实现方式
const statics = {
mhtml: {
top:
'Mime-Version: 1.0\nContent-Base: ' +
location.href +
'\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
location.href +
'\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
body: '<body>_body_</body>',
},
};
const content = ' ' + document.getElementById('exportContent')?.innerHTML.toString() || '';
// gigi 原生 实现方式
const mhtmlBottom = '\n';
const fileContent =
statics.mhtml.top.replace(
'_html_',
statics.mhtml.head.replace('_styles_', '') + statics.mhtml.body.replace('_body_', content),
) + mhtmlBottom;
const blob = new Blob([fileContent], { type: 'application/msword;charset=utf-8' });
const href = window.URL.createObjectURL(blob);
const a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
a.href = href;
a.download = refName + '_' + employeeName;
a.click();
window.URL.revokeObjectURL(href);
};
const content = ' ' + document.getElementById('exportContent')?.innerHTML.toString() || '';
id为exportContent的元素里面的内容就是你要要下载的内容,eportContent里面的内容就是下方的table,因为我的需求是导出表格 所以使用的是table来布局,代码如下:
<table
className="printTable"
border="1"
cellSpacing="0"
border-collapse="collapse"
width="800"
>
<thead align="center">
<tr>
<td width="800" colSpan={4}>
<h1>
<strong>表格内容标题</strong>
</h1>
</td>
</tr>
</thead>
<tbody>
<tr>
<td width="400">
内容1
</td>
<td width="400">
内容2
</td>
</tr>
</tbody>
</table>
这里注意如果有样式要求请通过style写行内样式或者写在 head里
head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n'
文档包含图片时需要先把图片转为base64
自定义文档名称通过:
a.download = '自定义文档名称',如果没有自定义名称会根据当前下载时间生成文档名字。