python - 如何将临时 .docx 文件添加到 django 中的 zip 存档中

标签 python django zip python-docx

这是我下载 zip 文件的代码,其中包含 .docx 文件,

def reportsdlserien(request):
    selected_sem = request.POST.get("semester","SS 2016")

    docx_title="Report_in_%s.docx" % selected_sem.replace(' ','_')

    document = Document()
    f = io.BytesIO()

    zip_title="Archive_in_%s.zip" % selected_sem.replace(' ','_')
    zip_arch = ZipFile( f, 'a' )

    document.add_heading("Report in "+selected_sem, 0)
    document.add_paragraph(date.today().strftime('%d %B %Y'))

    document.save(docx_title)
    zip_arch.write(docx_title)
    zip_arch.close()
    response = HttpResponse(
        f.getvalue(),
        content_type='application/zip'
    )
    response['Content-Disposition'] = 'attachment; filename=' + zip_title
    return response

唯一的问题是,它还会创建我不需要的 .docx 文件。我也想将 BytesIO 用于 docx 文件,但无法将其添加到存档中,命令 zip_arch.write(BytesIOdocxfile) 不起作用。还有另一个命令可以做到这一点吗? 谢谢!

最佳答案

使用writestr()向存档添加一些字节的函数:

data = StringIO()
document.save(data)  # Or however the library requires you to do this.
zip_arch.writestr(docx_title, bytes(data.getvalue()))

我只使用 StringIO 完成了此操作,但我不明白为什么 BytesIO 不能同样工作。

关于python - 如何将临时 .docx 文件添加到 django 中的 zip 存档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559238/

相关文章:

c# - 将 updateEntry() 方法与 dotnetzip 一起使用不会正确覆盖文件

Python:无法保存到 CSV

python - 这个变量声明在 python 中如何工作?

django - 使用Django的单页应用程序

python - Prefetch_related() 加入第一项

Python 导入 - 引用顶级模块而不是 "In-Level"模块

python-3.x - 本地下载zip文件到tempfile,解压文件到tempfile,列出文件

python - 如何使用 Python 将文本文件中的数据插入到 SQL Server 表中?

python - 使用 Python 将颜色图/渐变图应用于图像

java - 如何在 java 中定期刷新 ZipOutputStream