Search code examples
javascriptcsvexport-to-csvfilesaver.js

The attachement csv file not well formatted after getting blob data


I'm trying to download a csv file received from the server using FileSaver on React:

import FileSaver from 'file-saver';

const getFile = async (url) => {
  const response = await fetch(url);
  const data = await response.blob();

  return FileSaver.saveAs(data, 'file.csv');
}

The file is downloaded but the problem is not formatted well as csv file. I got this schema when I opened it:

col_header1;col_header1;col_header1
EQUAL t1;EQUAL v1;EQUAL R1
EQUAL t1;EQUAL v2;EQUAL R2
EQUAL t1;EQUAL v1;EQUAL R3

all the data are in a single column not in different ones. Is there anything to add to format it automatically before opening it ?


Solution

  • I resolved the issue by adding a separator to the date at the beginning:

    import FileSaver from 'file-saver';
    
    const getFile = async (url) => {
      const response = await fetch(url);
      const data = await response.text();
      const csvData = 'sep=;\n' + data;
      const blob = new Blob([csvData], {type: 'text/csv;charset=utf-8;'});
    
      return FileSaver.saveAs(data, 'file.csv');
    }