Create CVS file using javascript blob

Let’s start defining an array of objects containing the data we want to include in the CSV file.

const operations = [
  {
    id: '3c4db26d-6aec-4d4d-b9e7-86f8e05d6762',
    operation: 'buy',
    currency: 'EUR',
    amount: 1000
  },
  {
    id: '7eeda6db-2d86-47e9-a647-2d483f7c9769',
    operation: 'buy',
    currency: 'USD',
    amount: 1205
  },
  {
    id: '4ff58f69-10ee-40b5-9692-6875775359fc',
    operation: 'sell',
    currency: 'EUR',
    amount: 750
  }
]

Given that structure we want to create a CSV file containing the operation made, with the curerncy and amount.

Let’s start by defining the columns header:

const header = 'Operation,amount\r\n';

define the function to create the content:

const generateCSVOperationsContent = (operations) => {
  const csvRows = operations.map(operation => {
    const { operation: buySell, currency, amount } = operation;
    return `${buySell},${currency} ${amount}`;
  });
  return csvRows;
};

define the function to create the blob:

const generateCSVBlobContent = (header, csvRows) => {
  const csv = header.concat(csvRows.join('\r\n'));
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  return blob;
};

finally create the link to download the file:

const downloadBlob = (blob, filename) => {
  const link = document.createElement('a');
  link.download = filename;
  link.href = URL.createObjectURL(blob);
  link.target = '_blank';
  link.click();
  URL.revokeObjectURL(link.href);
};

now we can put all the pieces toghether:

const csvRows = generateCSVOperationsContent(operations);
const blob = generateCSVBlobContent(header, csvRows);
downloadBlob(blob, 'operations.csv');

This operation will download directly the file without opening a save as dialog window.

Download CSV

Published: Aug 27, 2022