gpt4 book ai didi

javascript - 将 JavaScript 循环导出到 CSV

转载 作者:行者123 更新时间:2023-12-02 23:28:36 24 4
gpt4 key购买 nike

假设我有这个循环代码。

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));

我该怎么办?我对此很陌生。谢谢。

最佳答案

此解决方案采用 JavaScript 语言。我向按钮添加了一个事件监听器,因此当单击它时,它将获取 outerHTML<table> .

outerHTML本质上包括元素的开始和结束标签以及内容,而 innerHTML 包括开始和结束标记。

来自MDN Web Docs

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

innerText从所有行和列中提取。 download_csv被调用。

您可以使用 Blob 下载数据对象是 file-like object of immutable, raw data

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>

关于javascript - 将 JavaScript 循环导出到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com