python - 在django中下载和保存文档的问题

标签 python django pandas django-views django-forms

我有几个问题,无法弄清楚,也许有联系。
问题 1.1:文件在 django 文档中导出并且它可以工作,但是当我尝试重命名它时,它有一些错误。我要这样with pd.ExcelWriter(newdoc + 'output.xlsx') as writer:为了每个文件都有一个"new"名称。
我收到这个错误,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})

最佳答案

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"

关于python - 在django中下载和保存文档的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69013296/

相关文章:

javascript - 模型表单中的 Django 自动 slug

python - 如何根据列的值将小型 pandas.dataframe 融合为较大的 pandas.dataframe ?

python - Pandas 数据框分组和求和,在组内,跨行值而不是按列

python - 当我想存储这样复杂的数据时,如何设计models.py?

python - 为什么 cx_freeze 包含我尚未导入的模块

python - PyQt 进度条 QThread 无法正常工作

django - 计算两个 PointField 之间的距离 - 为什么我的结果不正确?

python : Manipulating Arguments from a list of objects.

django - 我可以从 Django 的模板访问 settings.py 中的常量吗?

python - 用模式填充条形图