Home > database >  # character breaks content for CSV file during download
# character breaks content for CSV file during download

Time:10-13

I have code for downloading CSV file from some data.

  const rows = [ ["Html", "Css", "JavaScript"], ["C #", "C  ", "Python"] ];

   let csvContent = "data:text/csv;charset=utf-8," 
            rows.map(e => e.join(",")).join("\n"); 
 const encodedUri = encodeURI(csvContent);
 const link = document.createElement("a");
 link.setAttribute("href", encodedUri);
 link.setAttribute("download", "my_data.csv");
 document.body.appendChild(link); // Required for FF
 link.click();     

WITH # character

When I remove # character from data everything works fine

Without # character

As I understand encodeURL is not encode special symbols that is why href atribute includes # symbhol and ignore all after it.

I tryied to use Blob too but no result.

CodePudding user response:

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI?retiredLocale=it :

encodeURI() escapes all characters except:

A-Z a-z 0-9 ; , / ? : @ & =   $ - _ . ! ~ * ' ( ) #

Use encodeURIComponent instead, but only on the data part, not the whole url. Also note that to let Excel split the fields I have to use the semicolon, the comma doesn't work, but this could be because my locale settings.

const rows = [ ["Html", "Css", "JavaScript"], ["C #", "C  ", "Python"] ];
let csvContent = rows.map(e => e.join(";")).join("\n");
const encodedUri = "data:text/csv;charset=utf-8,"   encodeURIComponent(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click();
  • Related