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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 20:12:12338browse

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

Exporting JavaScript Array Data to CSV (Client-Side)

Exporting data from JavaScript arrays to CSV format can be a useful task for various scenarios. Here's a comprehensive method to accomplish this on the client side:

Parse Data into CSV Format

Firstly, convert your array of arrays into the correct CSV format. This involves joining each row of data with commas and separating rows using new lines. For instance:

const rows = [
  ["name1", "city1", "some other info"],
  ["name2", "city2", "more info"]
];

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

rows.forEach(function (rowArray) {
  let row = rowArray.join(",");
  csvContent += row + "\r\n";
});

or, using arrow functions:

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("\n");

Download CSV File

Next, use JavaScript's window.open and encodeURI functions to trigger a file download:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Custom File Name (Optional)

To specify a custom file name, use this approach:

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

The above is the detailed content of How Can I Export JavaScript Array Data 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