Home >Web Front-end >JS Tutorial >How to Export a JavaScript Array to a CSV File on the Client-Side?
Question:
How can JavaScript be used to export an array of data such as [["name1", "city_name1", ...]["name2", "city_name2", ...], to a CSV file on the client side?
Answer:
Using Native JavaScript:
rows.forEach(function(rowArray) { let row = rowArray.join(","); csvContent += row + "\r\n"; });
or
csvContent += rows.map(e => e.join(",")).join("\n");
const csvContent = "data:text/csv;charset=utf-8," + encodedCsvData;
var encodedUri = encodeURI(csvContent); window.open(encodedUri);
Customizing the CSV File Name:
To specify a custom name for the CSV file:
var link = document.createElement("a");
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
The above is the detailed content of How to Export a JavaScript Array to a CSV File on the Client-Side?. For more information, please follow other related articles on the PHP Chinese website!