【问题标题】:Downloading UTF-8-sig csv file to user将 UTF-8-sig csv 文件下载给用户
【发布时间】:2020-06-26 17:55:59
【问题描述】:

我将content_typeto_csv encoding 都设置为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')

然后,

在 javascript 中发送 csv 给用户

//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);
  };
}());

但它仍然是utf-8 而不是utf-8-sig (因为我不能用excel打开这个)

有什么地方需要检查吗??????

【问题讨论】:

  • 我猜 javascript 将响应标头设置为 octet/stream?
  • 我将它切换到 text/csv 但问题仍然存在...

标签: javascript python django unicode character-encoding


【解决方案1】:

我在下面这样解决了。

只需在 Javascript 中添加 bom。

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);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2020-12-09
    • 2021-03-09
    相关资源
    最近更新 更多