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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 20:31:11224browse

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

Exporting JavaScript Array Data to CSV on the Client Side

Question:

How can I export an array of data in JavaScript format to a CSV file on the client side?

Answer:

Using native JavaScript, you can transform your data into the correct CSV format, which involves joining rows and separating them with commas. Here's a step-by-step explanation:

1. Create the CSV Content:

// Assuming an array of arrays
const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

// Initialize CSV content
let csvContent = "data:text/csv;charset=utf-8,";

// Loop through rows and join them with commas
rows.forEach((rowArray) => {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

2. Download the CSV File:

// Encode the CSV content
var encodedUri = encodeURI(csvContent);

// Open the downloaded window with the encoded URI
window.open(encodedUri);

3. Specify File Name (Optional):

If you want to specify a particular file name, you'll need to use a different approach:

// Create a hidden <a> DOM node
var link = document.createElement("a");

// Set download attributes
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");

// Append to body (required for Firefox)
document.body.appendChild(link);

// Download the file
link.click();

This modified approach allows you to specify the file name as "my_data.csv" in this example.

The above is the detailed content of How to Export a JavaScript Array to a CSV File 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