Skip to main content
 首页 » 编程设计

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

2024年10月25日37qlqwjy

这是我下载 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 不能同样好地工作。