Python导出含有中文名文件解决方案

使用Python开发过程中有用到需要导出文件的功能
异常代码
# 代码片段
def return_workbook(self, workbook, model_code, x_io):
    name = “税单.xls”
    workbook.close()
    res = HttpResponse()
    res["Content-Type"] = "application/octet-stream"
    res["Content-Disposition"] = 'filename="{}.xlsx'.format(name)
    res.write(x_io.getvalue())
    return res
导出后文件名异常

在这里插入图片描述

修复后
# 代码片段

def return_workbook(self, workbook, model_code, x_io):
    name = “税单.xls”
    workbook.close()
    res = HttpResponse()
    res["Content-Type"] = "application/octet-stream"
    from django.utils.encoding import escape_uri_path
    res["Content-Disposition"] = 'filename="{}.xlsx'.format(escape_uri_path(name))
    res.write(x_io.getvalue())
    return res
导出后文件名正常显示

在这里插入图片描述

你可能感兴趣的:(django,python,后端)