鱼C论坛

 找回密码
 立即注册
查看: 2296|回复: 1

django ajax 下载excel 中文乱码怎么解决?

[复制链接]
发表于 2023-5-16 09:39:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 makliu 于 2023-5-16 09:39 编辑

如题,   df 的 数据如果 存在中文, 那么中文 就会显成乱码,  这个要怎么解决??

views代码如下
  1. def export_excel(request):
  2.     try:        
  3.         tableName = "tttt"        
  4.         df = pd.DataFrame([["1", "我是谁", "甘呈"], ["2", "你是谁", "甘要呈"]], columns=['id', 'name', 'age'])
  5.         response = HttpResponse()
  6.         response['Content-Type'] = 'application/vnd.ms-excel'
  7.         response['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(tableName)
  8.         response['Accept-Encoding'] = 'gzip, deflate, br'
  9.         out = _convert_df_to_bytes(df)
  10.         if not out:
  11.             raise RuntimeError("xxx")
  12.         response.write(out.getvalue())
  13.         return response
  14.     except Exception as e:
  15.         return e

  16. def _convert_df_to_bytes(df):
  17.     output = io.BytesIO()  # todo 50M nginx
  18.     df.to_csv(output, index=False, encoding="utf8")
  19.     output.seek(0)
  20.     return output
复制代码




ajax 代码如下:
  1. // 导出按钮
  2.     function bindExport(){
  3.         $("#btn_export").click(function () {
  4.                 var queryParams = {"arg1": "xxx", "arg2": "yyy"};
  5.            
  6.                 var xhr = new XMLHttpRequest();
  7.                 var url = "/export_excel/";
  8.                 xhr.responseType = "arraybuffer";
  9.                 xhr.open("get", url, true);
  10.                 xhr.onload = function () {
  11.                     const blob = new Blob([this.response], {type:"application/vnd.ms-excel"});
  12.                     if(blob.size < 1) {
  13.                         alert('导出失败,导出的内容为空!');
  14.                         return;
  15.                     }
  16.                     if(window.navigator.msSaveOrOpenBlob) {
  17.                         navigator.msSaveOrOpenBlob(blob, 'test.xls')
  18.                     } else {
  19.                         const aLink = document.createElement('a');
  20.                         aLink.style.display = 'none';
  21.                         aLink.href = window.URL.createObjectURL(blob);
  22.                         aLink.download = 'test.xls';
  23.                         document.body.appendChild(aLink);
  24.                         aLink.click();
  25.                         document.body.removeChild(aLink);
  26.                         return;
  27.                     }
  28.                 }
  29.                 xhr.setRequestHeader("Authorization", "xxx");
  30.                 xhr.setRequestHeader("Content-Type", "application/json");
  31.                 xhr.send(JSON.stringify(queryParams));
  32.             
  33.         });
  34.     };
复制代码



这样导出是 中文是乱码,  这要怎么解决???
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-5-16 09:39:47 | 显示全部楼层
在导出Excel时,中文乱码的问题通常是由于编码问题引起的。在这种情况下,您可以将编码设置为“utf-8”,以确保中文字符正确显示。

在您的代码中,您可以通过在 to_csv 函数中设置 encoding 参数为“utf-8”来解决这个问题。修改_convert_df_to_bytes函数的代码如下:
  1. def _convert_df_to_bytes(df):
  2.     output = io.BytesIO()
  3.     df.to_csv(output, index=False, encoding="utf-8") # 将 encoding 参数设置为 utf-8
  4.     output.seek(0)
  5.     return output
复制代码

这应该会解决您的中文乱码问题。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 01:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表