[英]Export javascript loop to CSV
假设我有这个循环代码。
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
outputDiv.innerHTML += results[j].distance.text + ',';
}
}
我想使用此代码将outputDiv.innerHTML导出到CSV,但是它不起作用。
function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
aLink.download = fileName;
aLink.href = urlData;
var event = new MouseEvent('click');
aLink.dispatchEvent(event);
}
downloadFile('output.csv', 'outputDiv.innerHTML/csv;charset=UTF-8,' + encodeURIComponent(outputDiv.innerHTML));
我该怎么办? 我是新来的。 谢谢。
它使用http://danml.com/js/download.js上的库,确保您的div内容包含逗号分隔的内容。
var csv = jQuery(".list").map(function(a, i) { return $.trim($(this).text()).split(/\\s*\\n\\s*/).join(","); }).toArray().join("\\r\\n"); alert(csv); // Contents // Download // download(csv, "tabledata.csv", "text/csv");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="http://danml.com/js/download.js"></script> <!-- CSV --> <div class="list"> 1, 2, 3 </div>
此解决方案使用JavaScript 。 我在按钮上添加了一个事件侦听器,因此在单击该按钮时,它将捕获<table>
的outerHTML
。
outerHTML
本质上包括元素的开始和结束标签以及内容,而innerHTML
不包括元素的开始和结束标签。
Element DOM接口的
outerHTML
属性获取描述元素(包括其后代)的序列化HTML片段。 也可以设置为将元素替换为从给定字符串解析的节点。
从所有行和列中提取innerText
。 download_csv
调用download_csv
。
您可以使用Blob
对象下载数据,该对象是不可变的原始数据的类似文件的对象 。
document.querySelector("button").addEventListener("click", function () { let html = document.querySelector("table").outerHTML; exportToCSV(html, "table.csv"); }); function exportToCSV(html, filename) { let csv = []; // grab all rows inside table let rows = document.querySelectorAll("table tr"); let row, cols; for (let i = 0; i < rows.length; i++) { row = []; // will hold innerText of all columns // retrieve all columns of row cols = rows[i].querySelectorAll("td, th"); for (let j = 0; j < cols.length; j++){ // push column innerText row.push(cols[j].innerText); } // push all innerText into CSV csv.push(row.join(",")); } console.log("Extracted content from html:",csv); // Download CSV download_csv(csv.join("\\n"), filename); } function download_csv(csv, filename) { let csvFile; let downloadLink; // CSV FILE csvFile = new Blob([csv], {type: "text/csv"}); // create an element and set the file name. downloadLink = document.createElement("a"); downloadLink.download = filename; // We have to create a link to the file downloadLink.href = window.URL.createObjectURL(csvFile); // prevent link from being shown downloadLink.style.display = "none"; // Add the link to your DOM document.body.appendChild(downloadLink); // start the download downloadLink.click(); }
<table> <tr><th>Name</th><th>Age</th><th>Country</th></tr> <tr><td>Tony</td><td>26</td><td>USA</td></tr> <tr><td>Levi</td><td>19</td><td>Spain</td></tr> <tr><td>Calvin</td><td>32</td><td>Russia</td></tr> </table> <button>Export HTML table to CSV file</button>
我不知道您要在最后一行中实现什么,但这看起来不像dataURL,dataURL看起来像:
数据:[] [; base64],
话虽如此,我们的想法是通过Blob
和window.URL.createObjectURL
的组合来创建对象url:
function dL(input,fileName){
var blob = new Blob(input,{type:"text/csv"}),
url = window.URL.createObjectURL(blob),
aElem = document.createElement("a"),
fileName = "deogenResults.txt";
aElem.setAttribute("href",url);
aElem.setAttribute("download",fileName);
if (window.navigator.constructor.prototype.hasOwnProperty("msSaveBlob")) {
window.navigator.msSaveBlob(blob,fileName);
} else if ("download" in aElem) {
aElem.click();
} else {
window.open(url,"_blank");
}
setTimeout(function(){window.URL.revokeObjectURL(url)},2000);
}
像这样使用它: dL(outputDiv.innerHTML,"someName")
它提醒你重要的是,一些浏览器可能不允许点击触发,是不是在DOM中又一个元素上,在这种情况下,你可能希望将一个元素追加到身体,将其不可见,然后将其删除里面的setTimeout 。
我用普通的ES5编写了它,可以相应地使用const
,Promise而不是setTimeout等声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.