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
Release: 2024-12-10 12:09:11
Original
546 people have browsed it

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";
});
Copy after login

or

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

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");
Copy after login
  1. Set the download attribute:
link.setAttribute("download", "my_data.csv");
Copy after login
  1. Append the node to the document body:
document.body.appendChild(link);
Copy after login
  1. Click the link to initiate the download:
link.click();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template