How to Export Javascript Array Info to Csv (on Client Side)?

As a tech professional working with JavaScript, you may often come across the need to export array information to a CSV file on the client side. In this blog post, we will explore different solutions to achieve this task.

Solution 1: Using Blob and URL.createObjectURL

The first solution involves creating a Blob object from the array data and then generating a download link using the created URL. Here’s an example:

// Example array data
const arrayData = [
  ['Name', 'Age', 'Email'],
  ['John Doe', 25, 'johndoe@example.com'],
  ['Jane Smith', 30, 'janesmith@example.com'],
];

// Create CSV content
const csvContent = arrayData.map(row => row.join(',')).join('n');

// Create a Blob object
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

// Create a download link
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'data.csv';
downloadLink.click();

When you run this code, it will automatically download a file named “data.csv” containing the array data in CSV format.

Solution 2: Using CSV file creation libraries

If you prefer a more structured approach, you can use JavaScript libraries specifically designed for creating CSV files. One such library is node-csv. Although it is primarily designed for server-side usage, you can still use it on the client side with the help of bundlers like Webpack or Browserify. Here’s an example:

// Example array data
const arrayData = [
  ['Name', 'Age', 'Email'],
  ['John Doe', 25, 'johndoe@example.com'],
  ['Jane Smith', 30, 'janesmith@example.com'],
];

// Import the CSV library
const { stringify } = require('csv');

// Convert array data to CSV format
stringify(arrayData, (err, output) => {
  if (err) throw err;

  // Create a download link
  const downloadLink = document.createElement('a');
  downloadLink.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(output);
  downloadLink.download = 'data.csv';
  downloadLink.click();
});

This code uses the stringify function from the csv library to convert the array data to CSV format. The resulting CSV content is then used to create a download link, similar to the first solution.

These are two common solutions to export JavaScript array information to a CSV file on the client side. Choose the one that best suits your needs and integrate it into your project.

Remember to always test your code thoroughly and handle any potential errors gracefully. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *