Thursday, May 14, 2015

How to Create Excel file with Images and Trigger to Download in Django ?



How to Create Excel file  and Trigger to Download in  Django ?


Install   :  pip install xlsxwriter


Dont Forget To import the following packages in your views


from django.shortcuts import render
from django.http import HttpResponse
from excel_response import ExcelResponse
import datetime as date_time
from django.utils.html import strip_tags
import io
from xlsxwriter.workbook import Workbook
import urllib2

import base64



Code Here

Here "Product" Is model

@login_required
def download_excel(request,p_id):

if p_id:
output = io.BytesIO()
workbook = Workbook(output, {'in_memory': True})
bold = workbook.add_format({'bold': True})
worksheet = workbook.add_worksheet()
merge_format = workbook.add_format({
'bold': 1,
'border': 1,
'align': 'center',
'valign': 'vcenter',
'fg_color': 'yellow'})
product = Product.objects.get(id=p_id)
worksheet.merge_range('A2:M2',"Product Name :"+product.name, merge_format)

heading = ['ProductName','Product Upc','category','Manufacturer','Brand','Product Style Number','Length','Width','Height','Weight','Color','Size','Description']
for counter,head in enumerate(heading):
worksheet.write(4,counter,head,merge_format)
category = product.category.all()
for cat in category:
cat_name = cat.name
colour = []
for clr in product.color.all():
cr = clr.color
colour.append(cr)
size = []
for si in product.size.all():
s = si.size
size.append(s)
html = product.description
discription = strip_tags(html)
content = [product.name,product.upc,cat_name,product.brand.manufacturer.name,product.brand.name,product.style_number,product.length +':'+product.length_mi,product.width +':'+product.length_mi,product.height+':'+product.length_mi,product.weight+':'+product.weight_mi,colour,size,discription]
for counter,data in enumerate(content):
worksheet.write(6,counter,''.join(data))
worksheet.write(4,13,'NetWork Price',merge_format)
worksheet.write(6,13,product.network_price)
worksheet.write('A10:M10', 'Product Images:',merge_format)
gallery = []
row = 7
col = 0
for image in product.gallery.all():
url = settings.SITE_URL + image.image_thumbnail.url
image_data = io.BytesIO(urllib2.urlopen(url).read())
gallery.append(image_data)
for counter,image in enumerate(gallery):
row += 10+counter
worksheet.insert_image(row,col, url, {'image_data': image,'x_offset': 15, 'y_offset': 10})
workbook.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=%s.xlsx" %product.upc
return response


1 comment: