makliu 发表于 2023-5-16 09:39:30

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

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

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

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

def _convert_df_to_bytes(df):
    output = io.BytesIO()# todo 50M nginx
    df.to_csv(output, index=False, encoding="utf8")
    output.seek(0)
    return output



ajax 代码如下:
// 导出按钮
    function bindExport(){
      $("#btn_export").click(function () {
                var queryParams = {"arg1": "xxx", "arg2": "yyy"};
         
                var xhr = new XMLHttpRequest();
                var url = "/export_excel/";
                xhr.responseType = "arraybuffer";
                xhr.open("get", url, true);
                xhr.onload = function () {
                  const blob = new Blob(, {type:"application/vnd.ms-excel"});
                  if(blob.size < 1) {
                        alert('导出失败,导出的内容为空!');
                        return;
                  }
                  if(window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveOrOpenBlob(blob, 'test.xls')
                  } else {
                        const aLink = document.createElement('a');
                        aLink.style.display = 'none';
                        aLink.href = window.URL.createObjectURL(blob);
                        aLink.download = 'test.xls';
                        document.body.appendChild(aLink);
                        aLink.click();
                        document.body.removeChild(aLink);
                        return;
                  }
                }
                xhr.setRequestHeader("Authorization", "xxx");
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.send(JSON.stringify(queryParams));
            
      });
    };


这样导出是 中文是乱码,这要怎么解决???

isdkz 发表于 2023-5-16 09:39:47

在导出Excel时,中文乱码的问题通常是由于编码问题引起的。在这种情况下,您可以将编码设置为“utf-8”,以确保中文字符正确显示。

在您的代码中,您可以通过在 to_csv 函数中设置 encoding 参数为“utf-8”来解决这个问题。修改_convert_df_to_bytes函数的代码如下:

def _convert_df_to_bytes(df):
    output = io.BytesIO()
    df.to_csv(output, index=False, encoding="utf-8") # 将 encoding 参数设置为 utf-8
    output.seek(0)
    return output


这应该会解决您的中文乱码问题。
页: [1]
查看完整版本: django ajax 下载excel 中文乱码怎么解决?