calendar export

remotes/origin/1203
Ivan Kovalkovskyi 10 years ago
parent 65a908d9af
commit 3bfec01d65
  1. 76
      core/utils.py
  2. 25
      core/views.py
  3. 28
      templates/client/accounts/calendar.html
  4. 2
      templates/client/includes/accounts/calendar_list.html

@ -1,5 +1,9 @@
# -*- coding: utf-8 -*-
"""
http://www.simplistix.co.uk/presentations/python-excel.pdf
"""
import xlwt
import datetime
from django.core.exceptions import ObjectDoesNotExist
@ -12,6 +16,7 @@ CELL_STYLE_MAP = (
(bool, xlwt.easyxf(num_format_str='BOOLEAN')),
)
def multi_getattr(obj, attr, default=None):
attributes = attr.split(".")
for i in attributes:
@ -39,33 +44,64 @@ def get_column_cell(obj, name):
return attr
def queryset_to_workbook(queryset, columns, header_style=None, default_style=None, cell_style_map=None):
def queryset_to_workbook(queryset, columns, report_date = None):
# 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, 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, wrap True;'
'pattern: pattern solid, fore_color silver_ega;',
)
# creating workbook and adding sheet
workbook = xlwt.Workbook()
report_date = datetime.date.today()
sheet_name = u'My calendar {0}'.format(report_date.strftime('%Y-%m-%d'))
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)
sheet.insert_bitmap('')
if not header_style:
header_style = HEADER_STYLE
if not default_style:
default_style = DEFAULT_STYLE
if not cell_style_map:
cell_style_map = CELL_STYLE_MAP
obj = queryset[0]
# drawing head part with image
sheet.write_merge(0, 6, 0, 6, u'Мой календарь собитий на %s года' % report_date.strftime("%B %Y"), main_style)
for i in range(7):
sheet.row(i).set_style(xlwt.Style.easyxf('font:height 300;'))
sheet.insert_bitmap('/home/www/proj/media/logo.bmp', row=0, col=5, x=0, y=0, scale_x=0.3, scale_y=2)
# drawing headers
header_list = [u'#', u'Название события',u'Даты',u'Краткое описание',u'Место проведения', u'Заметка', u'Ссылка на событие']
for i, column in enumerate(columns):
header_list=[u'#', u'Название события',u'Даты',u'Краткое описание',u'Место проведения', u'Заметка', u'Ссылка на событие']
sheet.write(0, i, header_list[i], header_style)
sheet.write(8, i, header_list[i], header_style)
sheet.col(i).width = 8000
sheet.col(0).width = 2000
for x, obj in enumerate(queryset, start=1):
# fill data
for x, obj in enumerate(queryset, start=9):
for y, column in enumerate(columns):
value = getattr(obj, column)
style = default_style
for value_type, cell_style in cell_style_map:
if isinstance(value, value_type):
style = cell_style
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

@ -220,7 +220,7 @@ class PageList(ListView):
from django.http import HttpResponseRedirect
import datetime
class EditPage(UpdateView):
model = Page
@ -259,23 +259,30 @@ from django.utils.translation import get_language
from .utils import queryset_to_workbook
from exposition.models import Exposition
from conference.models import Conference
from django.core.urlresolvers import reverse
def download_workbook(request):
lang = get_language()
data = [(36539, 'expo'),(36602, 'expo')]#, (3033, 'conf'), (3053, 'conf')]
data = request.GET
qs = []
for obj in data:
if obj[1] == 'expo':
qs.append(Exposition.objects.language(lang).get(id=obj[0]))
for i,obj in enumerate(data):
if data.get('data[%i][name]'%i) == 'expo':
qs.append(Exposition.objects.language(lang).get(id=data['data[%i][value]'%i]))
elif data.get('data[%i][name]'%i) == 'conf':
qs.append(Conference.objects.language(lang).get(id=data['data[%i][value]'%i]))
elif obj[1] == 'conf':
qs.append(Conference.objects.language(lang).get(id=obj[0]))
earliest_event = qs[0].data_begin
for i, obj in enumerate(qs, start=1):
if obj.data_begin < earliest_event:
earliest_event = obj.data_begin
setattr(obj, 'number', i)
setattr(obj, 'dates', u'%s - %s'%(obj.data_begin.strftime('%d %B %Y'),obj.data_end.strftime('%d %B %Y')))
setattr(obj, 'full_place', u'%s, %s, %s' % (obj.country, obj.city, getattr(obj.place, 'name', '')))
setattr(obj, 'link', u'expomap.ru%s'%obj.get_absolute_url())
try:
setattr(obj, 'link', u'http://www.expomap.ru%s)'%obj.get_absolute_url())
except:
setattr(obj, 'link', u'http://www.expomap.ru%s)'%obj.get_permanent_url())
columns = (
'number',
@ -286,7 +293,7 @@ def download_workbook(request):
'participation_note',
'link')
workbook = queryset_to_workbook(qs, columns)
workbook = queryset_to_workbook(qs, columns, earliest_event)
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="My calendar.xls"'
workbook.save(response)

@ -28,16 +28,18 @@
{% if events|length > 0 %}
<div class="cl-sect">
<div class="cls-title">{{ days.15|date:"F"}}’{{ days.15|date:"y"}}</div>
{% include 'includes/accounts/calendar_list.html' with events=events %}
{% include 'client/includes/accounts/calendar_list.html' with events=events %}
</div>
<div class="cl-actions clearfix">
<div class="cla-title">{% trans 'Все / выделенные:' %}</div>
<div class="cla-btns">
<a class="button" id="btn_delete" href="#">{% trans 'удалить из расписания' %}</a>
<!--
<a class="button icon-calendar-o" href="#">{% trans 'ЭКСПОРТИРОВАТЬ В' %} <span class="lc">iCal</span></a>
<a class="button icon-save" href="#">{% trans 'сохранить в xls' %}</a>
<a id ='export' class="button icon-save" href="#">{% trans 'сохранить в xls' %}</a>
<!--<a class="button icon-calendar-o" href="#">{% trans 'ЭКСПОРТИРОВАТЬ В' %} <span class="lc">iCal</span></a>
<a class="button icon-save" href="#">{% trans 'сохранить в pdf' %}</a>
<a class="button icon-print" href="#">{% trans 'Распечатать' %}</a>
-->
@ -50,6 +52,24 @@
<a class="icon-back" href="/profile/calendar/?year={{ days.15|add_month:'-1'|date:'Y' }}&month={{ days.15|add_month:'-1'|date:'m' }}">{% trans 'Посмотреть прошедший календарь' %}</a>
</div>
</div>
<script>
$(function(){
$("#export").click(function(event){
event.preventDefault();
var list = $('.qwer');
var clear_list = [], obj = {name:'', value:''};
for (var i = 0; i < list.length; i++){
if(list[i].checked == true) {
clear_list.push({name:list[i].name, value:list[i].value});
}
}
console.log(clear_list);
var query = $.param({data:clear_list});
window.location.href = "/profile/calendar/export/?" + query;
});
})
</script>
{% endblock %}
{% block scripts %}

@ -38,7 +38,7 @@
</div>
<div class="check-wrap">
<label class="check"><input type="checkbox" name="{{ event.event_type }}" value="{{ event.id }}" /></label>
<label class="check"><input class="qwer" type="checkbox" name="{{ event.event_type }}" value="{{ event.id }}" /></label>
</div>
</li>

Loading…
Cancel
Save