You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

131 lines
4.6 KiB

# -*- coding: utf-8 -*-
"""
http://www.simplistix.co.uk/presentations/python-excel.pdf
"""
import xlwt
import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.utils.translation import get_language
import os
current_lang = get_language()[:2]
if current_lang == 'ru':
header_list = [u'#', u'Название события',u'Даты',u'Краткое описание',u'Место проведения', u'Заметка', u'Ссылка на событие']
main_header = u'Мой календарь собитий на {month} {year} года'
else:
header_list = [u'#', u'Event',u'Period',u'Short description',u'Place', u'Notes', u'Hyperlink']
main_header = u'My event calendar on {month} {year}'
HEADER_STYLE = xlwt.easyxf('font: bold on')
DEFAULT_STYLE = xlwt.easyxf()
CELL_STYLE_MAP = (
(datetime.date, xlwt.easyxf(num_format_str='DD/MM/YYYY')),
(datetime.time, xlwt.easyxf(num_format_str='HH:MM')),
(bool, xlwt.easyxf(num_format_str='BOOLEAN')),
)
def multi_getattr(obj, attr, default=None):
attributes = attr.split(".")
for i in attributes:
try:
obj = getattr(obj, i)
except AttributeError:
if default:
return default
else:
return '-'
return obj
def get_column_cell(obj, name):
try:
attr = multi_getattr(obj, name)
except ObjectDoesNotExist:
return ''
if hasattr(attr, '_meta'):
# A Django Model (related object)
return unicode(attr).strip()
elif hasattr(attr, 'all'):
# A Django queryset (ManyRelatedManager)
return ', '.join(unicode(x).strip() for x in attr.all())
return attr
def queryset_to_workbook(queryset, columns, report_date = None):
# localization
if current_lang == 'ru':
month_name = settings.MONTHES[report_date.strftime("%b").lower()]['name']
else:
month_name = report_date.strftime("%B")
# defining styles for different types of cells
main_style = xlwt.Style.easyxf(
"font: name Calibri, height 600, bold False;"
"borders: left thin, right thin, top thin, bottom thin;"
"alignment: horizontal left, vertical center, indent 7;"
"pattern: pattern solid, fore_colour white;"
)
header_style = xlwt.Style.easyxf(
'font: name Calibri, height 400, bold False;'
'borders: left no_line, right no_line, top thin, bottom thin;'
'alignment: horizontal center, shrink_to_fit True;'
'pattern: pattern solid, fore_color gray_ega;',
)
odd_style = xlwt.Style.easyxf(
'font: name Calibri, height 300, bold False;'
'borders: left thin, right thin, top thin, bottom thin;'
'alignment: horizontal center, vertical center, wrap True;'
'pattern: pattern solid, fore_color white;',
)
even_style = xlwt.Style.easyxf(
'font: name Calibri, height 300, bold False;'
'borders: left thin, right thin, top thin, bottom thin;'
'alignment: horizontal center, vertical center, wrap True;'
'pattern: pattern solid, fore_color silver_ega;',
)
# creating workbook and adding sheet
workbook = xlwt.Workbook()
report_date = report_date or datetime.date.today()
sheet_name = u'My calendar {0}'.format(report_date.strftime('%Y-%B'))
sheet = workbook.add_sheet(sheet_name)
# drawing head part with image
sheet.write_merge(0, 6, 0, 6, main_header.format(
month = month_name,year = report_date.strftime("%Y")), main_style)
for i in range(7):
sheet.row(i).set_style(xlwt.Style.easyxf('font:height 300;'))
sheet.insert_bitmap(os.path.join(settings.MEDIA_ROOT, 'logo.bmp'), row=0, col=5, x=0, y=0, scale_x=0.3, scale_y=2)
# drawing headers
for i, column in enumerate(columns):
sheet.write(8, i, header_list[i], header_style)
sheet.col(i).width = 8000
sheet.col(0).width = 2000
# fill data
for x, obj in enumerate(queryset, start=9):
for y, column in enumerate(columns):
try:
value = getattr(obj, column)
except:
value = "-"
if x % 2 == 0:
style = even_style
else:
style = odd_style
sheet.write(x, y, value, style)
return workbook