Django:openpyxl保存工作簿作为附件 [英] Django: openpyxl saving workbook as attachment
问题描述
所以我想保存工作簿作为附件,但我不知道如何让我们看到一个例子从openpyxl导入工作簿
导入get_column_letter
wb =工作簿(编码=')
utf-8')
dest_filename ='file.xlsx'
ws = wb.worksheets [0]
ws.title =range names
for col_idx in xrange(1 ,40):
col = get_column_letter(col_idx)
用于xrange(1,600)中的行:
ws.cell('%s%s'%(col,row))。 value ='%s%s'%(col,row)
ws = wb.create_sheet()
ws.title ='Pi'
ws.cell('F5')。 = 3.14
然后我尝试了:
response = HttpResponse(wb,content_type ='application / vnd.ms-excel')
response ['Content-Disposition'] ='attachment; filename =foo.xls'
返回响应
它的确返回xlsx文件文件只有对象不涉及文件的内容:
< openpyxl.workbook.Workbook对象在0x00000000042806D8>
有人可以帮助吗?
尝试一下:
from openpyxl.writer.excel import save_virtual_workbook
。 ..
response = HttpResponse(save_virtual_workbook(wb),content_type ='application / vnd.ms-excel')
save_virtual_workbook
是专为您的用例而设计的。这是一个docstring:
返回内存中的工作簿,适合Django响应。
Hi I have a quick question. I didn't find answer in internet maybe someone of you can help me.
So i want to save workbook as attachment but I don't know how lets see an example :
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
wb = Workbook(encoding='utf-8')
dest_filename = 'file.xlsx'
ws = wb.worksheets[0]
ws.title = "range names"
for col_idx in xrange(1, 40):
col = get_column_letter(col_idx)
for row in xrange(1, 600):
ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14
Then I tried :
response = HttpResponse(wb, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="foo.xls"'
return response
It's returning xlsx file indeed but in file there is only object adres not the content of file:
<openpyxl.workbook.Workbook object at 0x00000000042806D8>
Can someone help ?
Give it a try:
from openpyxl.writer.excel import save_virtual_workbook
...
response = HttpResponse(save_virtual_workbook(wb), content_type='application/vnd.ms-excel')
save_virtual_workbook
was specially designed for your use case. Here's a docstring:
"""Return an in-memory workbook, suitable for a Django response."""
这篇关于Django:openpyxl保存工作簿作为附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!