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

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 :", 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):
category = product.category.all()
for cat in category:
cat_name =
colour = []
for clr in product.color.all():
cr = clr.color
size = []
for si in product.size.all():
s = si.size
html = product.description
discription = strip_tags(html)
content = [,product.upc,cat_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(4,13,'NetWork Price',merge_format)
worksheet.write('A10:M10', 'Product Images:',merge_format)
gallery = []
row = 7
col = 0
for image in
url = settings.SITE_URL + image.image_thumbnail.url
image_data = io.BytesIO(urllib2.urlopen(url).read())
for counter,image in enumerate(gallery):
row += 10+counter
worksheet.insert_image(row,col, url, {'image_data': image,'x_offset': 15, 'y_offset': 10})
response = HttpResponse(, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=%s.xlsx" %product.upc
return response

1 comment:

  1. I like your blog, I read this blog please update more content on python, further check it once at python online training