ArticleZip > How To Export Javascript Array Info To Csv On Client Side

How To Export Javascript Array Info To Csv On Client Side

JavaScript is an essential language in the world of web development, and one common task developers often encounter is exporting data to CSV files. In this guide, we'll explore how you can export JavaScript array information to a CSV file directly on the client-side.

To achieve this, we'll be leveraging the Blob and URL objects in JavaScript. The Blob object represents a file-like object of raw data, while the URL object provides static methods used for handling URLs.

First, we need to create a function that converts an array to a CSV string. We can achieve this by iterating through the array, formatting the data, and joining everything with commas. Here's an example function that does just that:

Javascript

function convertArrayToCSV(arr) {
    const csv = arr.map(row => row.join(',')).join('n');
    return csv;
}

With this function in place, you can now call it with your array of data to get a CSV-formatted string. Next, we need to create a function that will actually trigger the download of this CSV file. Here's how you can do it:

Javascript

function downloadCSV(csv, filename) {
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        const link = document.createElement('a');
        if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

In this function, we first create a Blob object from the CSV string with the appropriate MIME type. The method then checks if the browser supports the `msSaveBlob` function, which is used in Internet Explorer. If not, it creates a link element, sets the necessary attributes for downloading, and triggers the download. Once the download is complete, the dynamically created link is removed from the document body.

To bring it all together, you can use these functions as follows:

Javascript

const data = [
    ['Name', 'Age', 'Country'],
    ['Alice', 30, 'USA'],
    ['Bob', 25, 'Canada'],
    ['Charlie', 35, 'UK']
];

const csvString = convertArrayToCSV(data);
downloadCSV(csvString, 'exported_data.csv');

Replace the `data` array with your own dataset and call the `downloadCSV` function to trigger the download of the CSV file with your data. Make sure to provide a suitable filename for the exported file.

By following these steps, you can easily export JavaScript array information to a CSV file on the client-side. This approach provides a simple and effective way to generate downloadable CSV files from your web applications. Happy coding!

×