I have written some data in xlxs file with help of xlsxwriter I want to export it so that it can be downloaded how is this possible
def export(request,pk):
import xlsxwriter
product_resources = ProductType.objects.get(pk=pk)
print(product_resources)
attr = product_resources.product_attributes.all()
r1=[]
r1.append(str(product_resources))
for i in range(0,len(attr)):
r1.append(str(attr[i]))
print(r1)
if(request.GET):
col=0
row=0
workbook = xlsxwriter.Workbook('Product.xlsx')
worksheet = workbook.add_worksheet()
for item in r1:
worksheet.write_string(row,col, item)
col+=1
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="product.xlsx"'
workbook.close()
return response
This is my method but I am getting a file which is empty and could not be opened
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=product.xlsx"
Just try this.
content-type you have used is for xls files.
Can you try this instead of your code.
def export(request,pk):
import xlsxwriter
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output,{'in_memory': True})
workbook = xlsxwriter.Workbook(output, {'remove_timezone': True})
product_resources = ProductType.objects.get(pk=pk)
print(product_resources)
attr = product_resources.product_attributes.all()
r1=[]
r1.append(str(product_resources))
for i in range(0,len(attr)):
r1.append(str(attr[i]))
print(r1)
if(request.GET):
col=0
row=0
worksheet = workbook.add_worksheet()
for item in r1:
worksheet.write_string(row,col, item)
col+=1
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=product.xlsx"
workbook.close()
return response
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.