本文主要和大家分享js实现动态导出字符串方法,希望能帮助到大家。
示例1: 利用blob动态导出字符串到excel:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>document</title>
<style media="screen">
.tablea {
border-collapse: collapse;
}
.tablea .title th {
height: 50px;
font-size: 24px;
font-family: '微软雅黑';
font-weight: 700;
}
.tablea tr th {
border: 1px #000 solid;
height: 40px;
background: #efefef;
}
.tablea tr td {
padding: 0 40px;
border: 1px #000 solid;
height: 40px;
text-align: center;
}
.tablea .footer td {
font-size: 20px;
font-weight: 700;
}
</style>
</head>
<body>
<table bordercolor="black" class="tablea">
<tr class="title">
<th colspan="4">学生信息</th>
</tr>
<tr>
<th>名字</th>
<th>性别</th>
<th>年龄</th>
<th>班级</th>
</tr>
<tr>
<td>小明</td>
<td>男</td>
<td>19</td>
<td>1班</td>
</tr>
<tr>
<td>小黄</td>
<td>男</td>
<td>20</td>
<td>2班</td>
</tr>
<tr>
<td>老王</td>
<td>男</td>
<td>29</td>
<td>3班</td>
</tr>
<tr class="footer">
<td colspan="4">总人数:3人</td>
</tr>
</table>
<script>
var ohtml = document.getelementsbyclassname('tablea')[0].outerhtml;
var excelhtml = `
<html>
<head>
<meta charset='utf-8' />
<style>
.tablea {
border-collapse: collapse;
}
.tablea .title th{
height: 50px;
font-size: 24px;
font-family: '微软雅黑';
font-weight: 700;
}
.tablea tr th {
border: 1px #000 solid;
height: 40px;
background: #efefef;
}
.tablea tr td {
padding: 0 40px;
border: 1px #000 solid;
height: 40px;
text-align: center;
}
.tablea .footer td {
font-size: 20px;
font-weight: 700;
}
</style>
</head>
<body>
${ohtml}
</body>
</html>
`;
var debug = { hello: "world" };
// var blob = new blob([json.stringify(debug, null, 2)],
// { type: 'application/json' });
var excelblob = new blob([excelhtml], { type: 'application/vnd.ms-excel' })
// 创建一个a标签
var oa = document.createelement('a');
// 利用url.createobjecturl()方法为a元素生成blob url
oa.href = url.createobjecturl(excelblob);
// 给文件命名
oa.download = '学生名单.xls';
// 模拟点击
oa.click();
</script>
</body>
</html>
示例2:
<script>
var content1 = "hhh1";
var content2 = "23332";
var blob = new blob([content1,content2],{type:"text/plain"});
var url = url.createobjecturl(blob);
var aele = document.createelement("a");
var btn = document.queryselector("button");
btn.onclick = function (param) {
aele.href = url;
aele.download = "测试下载数据";
aele.click(); // dom.click() 模拟一次该dom的点击事件
}
</script>
注意: dom.click(); 是模拟一次dom 的点击事件。
相关推荐:
常见js中字符串的属性和方法
javascript中字符串常用操作方法详解
javascript的字符串怎样使用
以上就是js实现动态导出字符串方法的详细内容。