美文网首页
django前端访问一个url会自动下载excel文件

django前端访问一个url会自动下载excel文件

作者: butters001 | 来源:发表于2020-03-31 10:47 被阅读0次
def export_excel(request):
    """
    导出excel
    :param requests:
    :return:
    """
    try:
        logs = Logs.objects.values()
        dt = pd.DataFrame(logs, columns=['ID', '时间', '类型', '日志内容'])
        # 导出excel
        output = io.BytesIO()
        dt.to_excel(output, index=False)
        output.seek(0)

        response = HttpResponse()
        response["Content-Type"] = "application/vnd.ms-excel"
        file_name = 'loginfo(' + datetime.datetime.now().strftime("%Y/%m/%d-%H:%M:%S") + ').xlsx'
        response['Content-Disposition'] = 'attachment;filename=%s' % file_name
        # response['Access-Control-Expose-Headers'] = 'Content-Disposition'
        response.write(output.getvalue())

        output.close()
        return response

    except Exception as e:
        logger.error(str(e))

    return JsonResponse({'code': 1})

自动判断文件类型下载

file_name = 'xxxxxxxxxx.xxx'
response = HttpResponse()
response["Content-Type"] = "multipart/form-data"
response['Content-Disposition'] = 'attachment;filename=%s' % file_name
response.write(file_data.encode('iso-8859-1'))
return response

新问题 2020/05/29更

下载文件 Content-Type 文件名中文乱码问题
Content-Disposition: =?utf-8?b?YXR0YWNobWVudDtmaWxlbmFtZT3mnKrlkb3lkI0udHh0?=
修改方法 使用指定编码,并告诉浏览器编码类型。 上面代码的
response['Content-Disposition'] = 'attachment;filename=%s' % file_name
改为

from django.utils.encoding import escape_uri_path
response['Content-Disposition'] = 'attachment;filename=%s' % escape_uri_path(file_name)

相关文章

网友评论

      本文标题:django前端访问一个url会自动下载excel文件

      本文链接:https://www.haomeiwen.com/subject/roziuhtx.html