javascript中的界面CVS导出

原生js常用到的导出CVS,不使用后台接口,仅仅使用js以下是相关的代码,请大家指导

<div>
<p id="name">名字:admin</p><p id="word">密码:123456</p>
<button onclick="exportCSV()">导出CSV</button>
</div>
<script>
function exportCSV() {
var contentCVS = '\ufeff';
contentCVS +=document.getElementById('name').innerText+"\n";
contentCVS +=document.getElementById('word').innerText;
downloadFile("页面.txt",contentCVS);
}
function downloadFile(fileName, fileContent) {
//创建一个a元素
var aEle = document.createElement("a"),
n = new Blob([fileContent]); // Blob 对象,其内容由参数中给定的数组串联组成
aEle.download = fileName,
aEle.href = URL.createObjectURL(n);
var mouseEve = document.createEvent("MouseEvents");
//该方法将初始化 Document.createEvent() 方法创建的合成 Event 对象的 type 属性、bubbles 属性和 cancelable 属性。
// 只有在新创建的 Event 对象被 Document 对象或 Element 对象的 dispatchEvent() 方法分派之前,才能调用 Event.initEvent() 方法。
mouseEve.initEvent("click", !1, !1),
aEle.dispatchEvent(mouseEve)
}
</script>
posted @ 2020-07-07 16:22  三寸日光  阅读(138)  评论(0)    收藏  举报