Module contain service for work with excel documents import io from dj

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
Module contain service for work with excel documents
"""
import io
from django.conf import settings
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
import urllib3
def get_wallpaper_in_xlsx(wallpapers):
"""
Write wallpapers queryset in xlsx document
:param wallpapers: wallpapers queryset
:return: xlsx workbook
"""
wb = Workbook()
ws = wb.active
right_align = Alignment(horizontal='right')
left_align = Alignment(horizontal='left')
# Write header column
ws.column_dimensions['A'].width = 25
ws.cell(column=1, row=1, value='Айди')
ws.cell(column=1, row=2, value='Название по умлочанию')
ws.cell(column=1, row=3, value='Количество загрузок')
ws.cell(column=1, row=4, value='Категории')
ws.cell(column=1, row=5, value='Превью'
).alignment = Alignment(vertical='center')
# Write all client data
col = 2
for wallpaper in wallpapers:
ws.column_dimensions[get_column_letter(col)].width = 56
# String preview data
ws.cell(column=col, row=1,
value=wallpaper.id).alignment = right_align
ws.cell(column=col, row=2,
value=wallpaper.title).alignment = right_align
ws.cell(column=col, row=3,
value=wallpaper.load_counter).alignment = right_align
# Categories preview data
categories_list = [category.default_title for
category in wallpaper.categories.all()]
categories = ', '.join('"{0}"'.format(w) for w in categories_list)
ws.cell(column=col, row=4,
value=categories).alignment = right_align
# Preview row
ws.cell(column=col,
row=5,
value='Тут должно быть превью'
).alignment = left_align
add_preview(ws, wallpaper.preview_16_9.name, col)
col += 1
wb.close()
return wb
def add_preview(ws, preview_name, col):
"""
Add preview image according environment
:param ws: work book active ref
:param preview_name:
:param col: column
"""
if settings.IS_PROD:
http = urllib3.PoolManager()
r = http.request('GET', settings.MEDIA_URL + preview_name)
image_file = io.BytesIO(r.data)
img = Image(image_file)
row = '5'
img_cell = get_column_letter(col) + row
ws.add_image(img, img_cell)
else:
row = '5'
img_cell = get_column_letter(col) + row
img = Image(settings.CODE_DIR + settings.MEDIA_URL + preview_name)
ws.add_image(img, img_cell)