【问题标题】:Troubles with downloading and saving a document in django在 django 中下载和保存文档的问题
【发布时间】:2021-09-01 11:57:12
【问题描述】:

我有几个问题,想不通,可能有连接。

问题 1.1: 文件在 django 文档中导出并且它可以工作,但是当我尝试重命名它时,它有一些错误。我想成为这样的with pd.ExcelWriter(newdoc + 'output.xlsx') as writer:,以便每个文件都有一个“新”名称。 我收到了这个错误,TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'

问题1.2:如何添加保存路径?

问题 2: 我可以下载文件但它是空的,并且文件的名称是 Donwload.xlsx。我也想变成这样,但是这有很多错误……

filename = newdoc + '_calculated.xlsx'
response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response

当我这样做时,我得到了这个......在终端UserWarning: Calling close() 上已经关闭的文件。这在浏览器中 TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str'

这是views.py,如果代码是这样的,没有错误,但我要下载空文档。

def my_view(request):
    if request.method == "POST":
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            output = io.BytesIO()    
            newdoc = request.FILES['docfile']

            dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])

            with pd.ExcelWriter('output.xlsx') as writer: #problem 1 
                for name, df in dfs.items():
                    #pandas code for uploaded excel file
                    out.to_excel(writer, sheet_name=name)
                 
            output.seek(0)

            response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download' #problem 2
            return response

    else:
        form = DocumentForm()
    return render(request, 'list.html', {'form': form})

【问题讨论】:

    标签: python django pandas django-views django-forms


    【解决方案1】:

    output = io.BytesIO() 您在此处创建的根本没有使用。

    尝试改变

    with pd.ExcelWriter('output.xlsx') as writer:

    writer = pd.ExcelWriter(output)

    否则 BytesIO 可能会被 ExcelWriter 关闭,然后 Django 会尝试再次关闭它。给你双重关闭错误。

    您的问题 2 似乎是类型错误。

    filename = newdoc + '_calculated.xlsx'
    

    你这里的newdoc不是一个字符串,而是一个“InMemoryUploadedFile”,你可能需要通过这样做来访问它的名字

    filename = f"{newdoc.name}_calculated.xlsx"
    

    【讨论】:

    • 效果很好!非常感谢!如果我可以问的话,我还有两个问题。关于保存文档,是否可以添加到此功能或创建新功能更好?并且...如何呈现 html 的输出?类似于这行代码return render(request, 'list.html', {'table': html})
    • add to this function or is it better to create new? 这部分我不太明白。您正在下载一个文件。我不确定您的 HTML 会是什么样子。当用户提交表单时,他们应该停留在同一页面上,并且应该会弹出一个下载对话框。
    • 是的,当他们上传文件时,他们会弹出下载文件的窗​​口。但我也想在同一页面上显示来自文档的表格,也为我提供了更多保存文档或其他内容的可能性。
    • 你不能同时做这两个。这是我建议你做的事情,在文件提交后渲染页面,然后在该页面中有另一个按钮以允许用户下载。 (或通过javascript触发下载)
    • 非常感谢!
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多