Ad

Downloading UTF-8-sig Csv File To User

I set both content_type and to_csvencoding as utf_8_sig

response = HttpResponse(content_type='text/csv;charset=utf_8_sig')
response['Content-Disposition'] = 'attachment; filename=somefilename.csv'

df.to_csv(path_or_buf=response,sep=',',float_format='%.2f',index=False,decimal=",",encoding='utf_8_sig')

and then ,

send csv to user in javascript

//ajax response
DownlodCsv(response);


const DownloadCsv = (function() {
  const a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  return function(data, fileName) {
    const blob = new Blob([data], {type: "octet/stream"}),
      url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };
}());

However it still utf-8 not utf-8-sig (because I can't open this by excel)

Is there any place I should to check?????

Ad

Answer

I solved like this below.

Just adding the bom in Javascript.

return function(data, fileName) {
    let bom  = new Uint8Array([0xEF, 0xBB, 0xBF]); // add here
    const blob = new Blob([bom,data], {type: "octet/stream"}), // add bom
      url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };
Ad
source: stackoverflow.com
Ad