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
Release: 2024-12-12 20:31:11
Original
245 people have browsed it

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

2. Download the CSV File:

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

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

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

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!

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