Home >Web Front-end >JS Tutorial >How to Export a JavaScript Array to a CSV File on the Client-Side?

How to Export a JavaScript Array to a CSV File on the Client-Side?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 12:09:11550browse

How to Export a JavaScript Array to a CSV File on the Client-Side?

Export JavaScript Array to CSV on 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:

  1. Parse the array data into the correct CSV format:
rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

or

csvContent += rows.map(e => e.join(",")).join("\n");
  1. Create a data URI with the CSV content:
const csvContent = "data:text/csv;charset=utf-8," + encodedCsvData;
  1. Open the CSV file for download:
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Customizing the CSV File Name:

To specify a custom name for the CSV file:

  1. Create a hidden DOM node:
var link = document.createElement("a");
  1. Set the download attribute:
link.setAttribute("download", "my_data.csv");
  1. Append the node to the document body:
document.body.appendChild(link);
  1. Click the link to initiate the download:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn