目录
1.场景
如下图所示,项目要求对页面中的数据下载到本地,并以某种类型展示,如Word、doc、html等。在这个项目中要求下载为doc文件和HTML文件,其实下载功能还是很简单的,关键的地方就是下载后的格式问题,比如doc其实就是表格或者文档的格式。
2.思路
我的思路是这样的,我会根据需求将需要导出的数据,在项目中找个地方以table、th表格标签的形式写,然后设置display:none,目的是不让多出来的结构影响到原本的页面,然后绑定ref,然后再通过模板字符串的形式,渲染出来。下面我是代码实例。
3.实现
第一步,准备数据,隐藏标签,绑定ref
// 1.准备数据,要下载的数据,以表格的形式书写。
<div ref={wrapperRef}>
<table style={{display: "none"}} className='table11_7 resultTable'>
<tr>
<th>序号</th>
<th>名称</th>
<th>是否存在漏洞</th>
{/* <th>开放情况</th> */}
</tr>
{list.map((ele, idx) => (
<tr className='tr'>
<td className='td td1'>{idx + 1}</td>
<td className='td td2'>{ele.data.Id}</td>
<td className='td td3'>{ele.data.status} </td>
{/* <td className='td td4'> </td> */}
</tr>
))}
</table>
</div>
第二步,通过模板字符串生成数据
需要注意的是,如果不以table标签书写,下载后的doc文件很乱,html则没事,所以还是尽量用table标签去写。
代码中的最后几行是下载功能,个人感觉是挺万金油的,可以根据需要下载为任意类型的文件
以下代码实例为,点击按钮下载。
<Button
onClick={(e) => {
let resHtml = `
<!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>Document</title>
<style>
.table11_7 table {
width:500px;
margin:15px 0;
border:0;
}
.table11_7 th {
background-color:#00A5FF;
color:#FFFFFF
}
.table11_7,.table11_7 th,.table11_7 td {
font-size:0.95em;
width:800px;
text-align:center;
padding:10px;
border-collapse:collapse;
}
.table11_7 th,.table11_7 td {
border: 1px solid #2087fe;
border-width:1px 0 1px 0;
border:2px inset #ffffff;
}
.table11_7 tr {
border: 1px solid #ffffff;
}
.table11_7 tr:nth-child(odd){
background-color:#aae1fe;
}
.table11_7 tr:nth-child(even){
background-color:#ffffff;
}
</style>
</head>
<body>
<div style="display:flex;">
<div> ${listRef.current.innerHTML}</div>
</div>
<div style="display:flex;">
<div style=" ">
${listRef3.current.innerHTML}</div>
</div>
</div>
</body>
</html>
`
var datastr = "data:text/html;charset=utf-8," + encodeURIComponent(resHtml)
var downloadAnchorNode = document.createElement("a")
downloadAnchorNode.setAttribute("href", datastr)
downloadAnchorNode.setAttribute(
"download",
`${localStorage.getItem("verboseNameRaw")}-${localStorage.getItem("isStart")}.html`
)
downloadAnchorNode.click()
downloadAnchorNode.remove()
}}
>
.HTML
</Button>