鱼C论坛

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

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

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

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

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

x
本帖最后由 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([this.response], {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));
            
        });
    };


这样导出是 中文是乱码,  这要怎么解决???
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 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
这应该会解决您的中文乱码问题。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-23 05:26

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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