因項目中要生成Excel 並返回
代碼
def file_iterator(file_name, chunk_size=512):
'''
# 用於形成二進制數據
:return:
'''
with open(file_name, 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
返回到前端
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
# instance = Design.objects.get(id=1)
name = "{}-{}.xlsx".format(instance.project.name, instance.name)
create_name = "design_{}.xlsx".format(instance.id)
path = os.path.join(BASE_DIR, "media", create_name)
import xlsxwriter
workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet("元件")
headings = ['名稱', '品牌', '規格', '數量']
worksheet.write_row("A1", headings)
pdetails = Details.objects.filter(design=instance,category__in=(1,2))
row = 1
for p in pdetails:
worksheet.write(row, 0, p.name)
worksheet.write(row, 1, p.brand)
worksheet.write(row, 2, p.size)
worksheet.write(row, 3, p.num)
row += 1
workbook.close()
###### 下面 返回生成的 Excel
file = file_iterator(path)
response = StreamingHttpResponse(file)
response['Content-Type'] = 'application/txt'
# 注意filename 這個是下載後的名字
response['Content-Disposition'] = 'attachment;filename="{}"'.format(name)
return response