python - 如何在django中设置excel文件的路径

标签 python django pandas

我正在使用 pandas ExcelWriter 和 openpyxl 在 Django 项目中创建 Excel。我如何在项目目录中设置特定路径来保存创建的Excel?谢谢,提前。

from pandas import ExcelWriter
df_view = obj_master.get_employee()
writer = ExcelWriter('PythonExportt.xlsx')
df_view.to_excel(writer, 'Sheet1')
writer.save()

最佳答案

可能最好的方法是将 Pandas Excel 流写入内存流,然后将其包装到 HTTP 响应中:

from pandas import ExcelWriter

XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

def some_excelfile_view(request):
    response = HttpResponse(content_type=XLSX_MIME)
    response['Content-Disposition'] = 'attachment; filename="PythonExport.xlsx"'

    # obtain obj_master
    # ...
    writer = pd.ExcelWriter(<b>response</b>, engine='xlsxwriter')

    df_view = obj_master.get_employee()
    df_view.to_excel(writer, 'Sheet1')
    writer.save()
    return response

然后您可以使用映射到此 some_excelfile_viewurl。如果用户随后访问该 URL,它将执行 Excel 文件的文件下载。

关于python - 如何在django中设置excel文件的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058841/

相关文章:

python - 遍历Python中的所有文件夹

python - matplotlib:在 3d 极坐标图中填充线下

python - 在 Django 中验证 Google ID token

python - Django、Borg 模式、API 调用、缓存结果

python - 尽管使用了正确的列名,但仍出现键错误

python - 基于列名在 pandas 数据框的 lambda 表达式上使用 if else 语句

python - 在写入命令中保留颜色

Python 字典 : TypeError: unhashable type: 'list'

python - 如何根据 James Bennett 的文章 "So you want a dynamic form"动态创建 ModelForm ?

python - 在 Pandas 中同时替换空白和空字段