forked from sahana/eden
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsurvey.py
1362 lines (1223 loc) · 48.7 KB
/
survey.py
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
survey - Assessment Data Analysis Tool
For more details see the blueprint at:
http://eden.sahanafoundation.org/wiki/BluePrint/SurveyTool/ADAT
@todo: open template from the dataTables into the section tab not update
@todo: in the pages that add a link to a template make the combobox display the label not the numbers
"""
module = request.controller
resourcename = request.function
if not settings.has_module(module):
raise HTTP(404, body="Module disabled: %s" % module)
try:
from cStringIO import StringIO # Faster, where available
except:
from StringIO import StringIO
from gluon.contenttype import contenttype
from s3survey import S3AnalysisPriority, \
survey_question_type, \
survey_analysis_type, \
getMatrix, \
DEBUG, \
LayoutBlocks, \
DataMatrix, MatrixElement, \
S3QuestionTypeOptionWidget, \
survey_T
# -----------------------------------------------------------------------------
def index():
""" Module's Home Page """
module_name = settings.modules[module].name_nice
response.title = module_name
return dict(module_name=module_name)
# -----------------------------------------------------------------------------
def template():
""" RESTful CRUD controller """
# Load Model
#table = s3db.survey_template
def prep(r):
if r.component:
if r.component_name == "translate":
table = s3db.survey_translate
if r.component_id == None:
# list existing translations and allow the addition of a new translation
table.file.readable = False
table.file.writable = False
else:
# edit the selected translation
table.language.writable = False
table.code.writable = False
# remove CRUD generated buttons in the tabs
s3db.configure("survey_translate",
deletable=False)
else:
table = r.table
s3_action_buttons(r)
# Status of Pending
rows = db(table.status == 1).select(table.id)
try:
s3.actions[1]["restrict"].extend(str(row.id) for row in rows)
except KeyError: # the restrict key doesn't exist
s3.actions[1]["restrict"] = [str(row.id) for row in rows]
except IndexError: # the delete buttons doesn't exist
pass
# Add some highlighting to the rows
# Status of Pending
s3.dataTableStyleAlert = [str(row.id) for row in rows]
# Status of closed
rows = db(table.status == 3).select(table.id)
s3.dataTableStyleDisabled = [str(row.id) for row in rows]
s3.dataTableStyleWarning = [str(row.id) for row in rows]
# Status of Master
rows = db(table.status == 4).select(table.id)
s3.dataTableStyleWarning.extend(str(row.id) for row in rows)
s3db.configure("survey_template",
orderby = "survey_template.status",
create_next = URL(c="survey", f="template"),
update_next = URL(c="survey", f="template"),
)
return True
s3.prep = prep
# Post-processor
def postp(r, output):
if r.component:
template_id = r.id
if r.component_name == "translate":
s3_action_buttons(r)
s3.actions.append(dict(label=str(T("Download")),
_class="action-btn",
url=URL(c=module,
f="templateTranslateDownload",
args=["[id]"])
),
)
s3.actions.append(
dict(label=str(T("Upload")),
_class="action-btn",
url=URL(c=module,
f="template",
args=[template_id, "translate", "[id]"])
),
)
#elif r.component_name == "section":
# # Add the section select widget to the form
# # undefined
# sectionSelect = s3.survey_section_select_widget(template_id)
# output.update(form = sectionSelect)
# Add a button to show what the questionnaire looks like
#s3_action_buttons(r)
#s3.actions = s3.actions + [
# dict(label=str(T("Display")),
# _class="action-btn",
# url=URL(c=module,
# f="templateRead",
# args=["[id]"])
# ),
# ]
return output
s3.postp = postp
if request.ajax:
post = request.post_vars
action = post.get("action")
template_id = post.get("parent_id")
section_id = post.get("section_id")
section_text = post.get("section_text")
if action == "section" and template_id != None:
id = db.survey_section.insert(name=section_text,
template_id=template_id,
cloned_section_id=section_id)
if id is None:
print "Failed to insert record"
return
# Remove CRUD generated buttons in the tabs
s3db.configure("survey_template",
listadd=False,
#deletable=False,
)
output = s3_rest_controller(rheader=s3db.survey_template_rheader)
return output
# -----------------------------------------------------------------------------
def templateRead():
"""
"""
if len(get_vars) > 0:
dummy, template_id = get_vars.viewing.split(".")
else:
template_id = request.args[0]
def postp(r, output):
if r.interactive:
template_id = r.id
form = s3db.survey_buildQuestionnaireFromTemplate(template_id)
output["items"] = None
output["form"] = None
output["item"] = form
output["title"] = s3.crud_strings["survey_template"].title_question_details
return output
s3.postp = postp
# remove CRUD generated buttons in the tabs
s3db.configure("survey_template",
listadd=False,
editable=False,
deletable=False,
)
r = s3_request("survey", "template", args=[template_id])
output = r(method = "read", rheader=s3db.survey_template_rheader)
return output
# -----------------------------------------------------------------------------
def templateSummary():
"""
"""
# Load Model
tablename = "survey_template"
s3db[tablename]
s3db.survey_complete
crud_strings = s3.crud_strings[tablename]
def postp(r, output):
if r.interactive:
if len(get_vars) > 0:
dummy, template_id = get_vars.viewing.split(".")
else:
template_id = r.id
form = s3db.survey_build_template_summary(template_id)
output["items"] = form
output["sortby"] = [[0, "asc"]]
output["title"] = crud_strings.title_analysis_summary
output["subtitle"] = crud_strings.subtitle_analysis_summary
return output
s3.postp = postp
# remove CRUD generated buttons in the tabs
s3db.configure(tablename,
listadd=False,
deletable=False,
)
output = s3_rest_controller("survey", "template",
method = "list",
rheader=s3.survey_template_rheader
)
s3.actions = None
return output
# -----------------------------------------------------------------------------
def templateTranslateDownload():
"""
Download a Translation Template
@ToDo: Rewrite as S3Method handler
"""
error_url = URL(c="survey", f="templateTranslation", args=[], vars={})
try:
translation_id = request.args[0]
except:
redirect(error_url)
try:
import xlwt
except ImportError:
redirect(error_url)
table = s3db.survey_translate
record = db(table.id == translation_id).select(table.code,
table.language,
table.template_id,
limitby=(0, 1)).first()
if record is None:
redirect(error_url)
code = record.code
language = record.language
lang_fileName = "applications/%s/languages/%s.py" % \
(appname, code)
try:
from gluon.languages import read_dict
strings = read_dict(lang_fileName)
except:
strings = dict()
template_id = record.template_id
# Load Model
table = s3db.survey_template
s3db.table("survey_complete")
template = db(table.id == template_id).select(table.name,
table.description,
limitby=(0, 1)).first()
book = xlwt.Workbook(encoding="utf-8")
sheet = book.add_sheet(language)
output = StringIO()
qstnList = s3.survey_getAllQuestionsForTemplate(template_id)
original = {}
original[template.name] = True
if template.description != "":
original[template.description] = True
for qstn in qstnList:
original[qstn["name"]] = True
widgetObj = survey_question_type[qstn["type"]](question_id = qstn["qstn_id"])
if isinstance(widgetObj, S3QuestionTypeOptionWidget):
optionList = widgetObj.getList()
for option in optionList:
original[option] = True
sections = s3.survey_getAllSectionsForTemplate(template_id)
for section in sections:
original[section["name"]] = True
section_id = section["section_id"]
layoutRules = s3.survey_getQstnLayoutRules(template_id, section_id)
layoutStr = str(layoutRules)
posn = layoutStr.find("heading")
while posn != -1:
start = posn + 11
end = layoutStr.find("}", start)
original[layoutStr[start:end]] = True
posn = layoutStr.find("heading", end)
row = 0
sheet.write(row,
0,
unicode("Original")
)
sheet.write(row,
1,
unicode("Translation")
)
originalList = original.keys()
originalList.sort()
for text in originalList:
row += 1
original = unicode(text)
sheet.write(row,
0,
original
)
if (original in strings):
sheet.write(row,
1,
strings[original]
)
book.save(output)
output.seek(0)
response.headers["Content-Type"] = contenttype(".xls")
filename = "%s.xls" % code
response.headers["Content-disposition"] = "attachment; filename=\"%s\"" % filename
return output.read()
# -----------------------------------------------------------------------------
def series():
""" RESTful CRUD controller """
# Load Model
table = s3db.survey_series
s3db.survey_answerlist_dataTable_pre()
def prep(r):
if r.interactive:
if r.method == "create":
allTemplates = s3db.survey_getAllTemplates()
if len(allTemplates) == 0:
session.warning = T("You need to create a template before you can create a series")
redirect(URL(c="survey", f="template", args=[], vars={}))
if r.id and (r.method == "update"):
table.template_id.writable = False
return True
s3.prep = prep
def postp(r, output):
if request.ajax == True and r.method == "read":
return output["item"]
if not r.component:
# Set the minimum end_date to the same as the start_date
s3.jquery_ready.append(
'''S3.start_end_date('survey_series_start_date','survey_series_end_date')''')
s3db.survey_serieslist_dataTable_post(r)
elif r.component_name == "complete":
if r.method == "update":
if r.http == "GET":
form = s3db.survey_buildQuestionnaireFromSeries(r.id,
r.component_id)
output["form"] = form
elif r.http == "POST":
if len(request.post_vars) > 0:
id = s3db.survey_save_answers_for_series(r.id,
r.component_id, # Update
request.post_vars)
response.confirmation = \
s3.crud_strings["survey_complete"].msg_record_modified
else:
s3db.survey_answerlist_dataTable_post(r)
return output
s3.postp = postp
# Remove CRUD generated buttons in the tabs
s3db.configure("survey_series",
deletable = False,)
s3db.configure("survey_complete",
listadd=False,
deletable=False)
output = s3_rest_controller(rheader=s3db.survey_series_rheader)
return output
# -----------------------------------------------------------------------------
def export_all_responses():
"""
Download all responses in a Spreadsheet
@ToDo: rewrite as S3Method handler
"""
try:
series_id = request.args[0]
import xlwt
except:
output = s3_rest_controller(module, "series",
rheader=s3db.survey_series_rheader)
return output
# Load Model
s3db.table("survey_series")
s3db.table("survey_section")
s3db.table("survey_complete")
# Turn off lazy translation
# otherwise xlwt will crash if it comes across a T string
T.lazy = False
seriesName = s3db.survey_getSeriesName(series_id)
sectionBreak = False
filename = "%s_All_responses.xls" % seriesName
contentType = ".xls"
output = StringIO()
book = xlwt.Workbook(encoding="utf-8")
# Get all questions and write out as a heading
col = 0
completeRow = {}
nextRow = 2
qstnList = s3db.survey_getAllQuestionsForSeries(series_id)
if len(qstnList) > 256:
sectionList = s3db.survey_getAllSectionsForSeries(series_id)
sectionBreak = True
if sectionBreak:
sheets = {}
cols = {}
for section in sectionList:
sheetName = section["name"].split(" ")[0]
if sheetName not in sheets:
sheets[sheetName] = book.add_sheet(sheetName)
cols[sheetName] = 0
else:
sheet = book.add_sheet(T("Responses"))
for qstn in qstnList:
if sectionBreak:
sheetName = qstn["section"].split(" ")[0]
sheet = sheets[sheetName]
col = cols[sheetName]
row = 0
sheet.write(row,col,qstn["code"])
row += 1
widgetObj = s3db.survey_getWidgetFromQuestion(qstn["qstn_id"])
sheet.write(row,col,widgetObj.fullName())
# For each question get the response
allResponses = s3db.survey_getAllAnswersForQuestionInSeries(qstn["qstn_id"],
series_id)
for answer in allResponses:
value = answer["value"]
complete_id = answer["complete_id"]
if complete_id in completeRow:
row = completeRow[complete_id]
else:
completeRow[complete_id] = nextRow
row = nextRow
nextRow += 1
sheet.write(row,col,value)
col += 1
if sectionBreak:
cols[sheetName] += 1
sheet.panes_frozen = True
sheet.horz_split_pos = 2
book.save(output)
# Turn lazy translation back on
T.lazy = True
output.seek(0)
response.headers["Content-Type"] = contenttype(contentType)
response.headers["Content-disposition"] = "attachment; filename=\"%s\"" % filename
return output.read()
# -----------------------------------------------------------------------------
def series_export_formatted():
"""
Download a Spreadsheet which can be filled-in offline & uploaded
@ToDo: rewrite as S3Method handler
"""
try:
series_id = request.args[0]
except:
output = s3_rest_controller(module, "series",
rheader=s3db.survey_series_rheader)
return output
# Load Model
s3db.table("survey_series")
s3db.table("survey_complete")
vars = request.post_vars
seriesName = s3db.survey_getSeriesName(series_id)
series = s3db.survey_getSeries(series_id)
if not series.logo:
logo = None
else:
if "Export_Spreadsheet" in vars:
ext = "bmp"
else:
ext = "png"
logo = os.path.join(request.folder,
"uploads",
"survey",
"logo",
"%s.%s" %(series.logo,ext)
)
if not os.path.exists(logo) or not os.path.isfile(logo):
logo = None
# Get the translation dictionary
langDict = dict()
lang = request.post_vars.get("translationLanguage", None)
if lang:
if lang == "Default":
langDict = dict()
else:
try:
from gluon.languages import read_dict
lang_fileName = "applications/%s/uploads/survey/translations/%s.py" % (appname, lang)
langDict = read_dict(lang_fileName)
except:
langDict = dict()
if "Export_Spreadsheet" in vars:
(matrix, matrixAnswers) = series_prepare_matrix(series_id,
series,
logo,
langDict,
justified = True
)
output = series_export_spreadsheet(matrix,
matrixAnswers,
logo,
)
filename = "%s.xls" % seriesName
contentType = ".xls"
elif "Export_Word" in vars:
template = s3db.survey_getTemplateFromSeries(series_id)
template_id = template.id
title = "%s (%s)" % (series.name, template.name)
title = survey_T(title, langDict)
widgetList = s3db.survey_getAllWidgetsForTemplate(template_id)
output = series_export_word(widgetList, langDict, title, logo)
filename = "%s.rtf" % seriesName
contentType = ".rtf"
else:
output = s3_rest_controller(module, "series",
rheader=s3db.survey_series_rheader)
return output
output.seek(0)
response.headers["Content-Type"] = contenttype(contentType)
response.headers["Content-disposition"] = "attachment; filename=\"%s\"" % filename
return output.read()
# -----------------------------------------------------------------------------
def series_prepare_matrix(series_id, series, logo, langDict, justified = False):
"""
Helper function for series_export_formatted()
"""
######################################################################
#
# Get the data
# ============
# * The sections within the template
# * The layout rules for each question
######################################################################
# Check that the series_id has been passed in
if len(request.args) != 1:
output = s3_rest_controller(module, "series",
rheader=s3db.survey_series_rheader)
return output
series_id = request.args[0]
template = s3db.survey_getTemplateFromSeries(series_id)
template_id = template.id
sectionList = s3db.survey_getAllSectionsForSeries(series_id)
title = "%s (%s)" % (series.name, template.name)
title = survey_T(title, langDict)
layout = []
survey_getQstnLayoutRules = s3db.survey_getQstnLayoutRules
for section in sectionList:
sectionName = survey_T(section["name"], langDict)
rules = survey_getQstnLayoutRules(template_id,
section["section_id"])
layoutRules = [sectionName, rules]
layout.append(layoutRules)
widgetList = s3db.survey_getAllWidgetsForTemplate(template_id)
layoutBlocks = LayoutBlocks()
######################################################################
#
# Store the questions into a matrix based on the layout and the space
# required for each question - for example an option question might
# need one row for each possible option, and if this is in a layout
# then the position needs to be recorded carefully...
#
######################################################################
preliminaryMatrix = getMatrix(title,
logo,
series,
layout,
widgetList,
False,
langDict,
showSectionLabels = False,
layoutBlocks = layoutBlocks
)
if not justified:
return preliminaryMatrix
######################################################################
# Align the questions so that each row takes up the same space.
# This is done by storing resize and margin instructions with
# each widget that is being printed
######################################################################
layoutBlocks.align()
######################################################################
# Now rebuild the matrix with the spacing for each widget set up so
# that the document will be fully justified
######################################################################
layoutBlocks = LayoutBlocks()
(matrix1, matrix2) = getMatrix(title,
logo,
series,
layout,
widgetList,
True,
langDict,
showSectionLabels = False,
)
return (matrix1, matrix2)
# -----------------------------------------------------------------------------
def series_export_word(widgetList, langDict, title, logo):
"""
Export a Series in RTF Format
@ToDo: rewrite as S3Method handler
"""
try:
from PyRTF import Document, \
Languages, \
Section, \
Image, \
Paragraph, \
ShadingPropertySet, \
ParagraphPropertySet, \
StandardColours, \
Colour, \
Table, \
Cell, \
Renderer
except ImportError:
output = s3_rest_controller(module, "survey_series",
rheader=s3db.survey_series_rheader)
return output
output = StringIO()
doc = Document(default_language=Languages.EnglishUK)
section = Section()
ss = doc.StyleSheet
ps = ss.ParagraphStyles.Normal.Copy()
ps.SetName("NormalGrey")
ps.SetShadingPropertySet(ShadingPropertySet(pattern=1,
background=Colour("grey light", 224, 224, 224)))
ss.ParagraphStyles.append(ps)
ps = ss.ParagraphStyles.Normal.Copy()
ps.SetName("NormalCentre")
ps.SetParagraphPropertySet(ParagraphPropertySet(alignment=3))
ss.ParagraphStyles.append(ps)
doc.Sections.append(section)
heading = Paragraph(ss.ParagraphStyles.Heading1)
if logo:
image = Image(logo)
heading.append(image)
heading.append(title)
section.append(heading)
col = [2800, 6500]
table = Table(*col)
AddRow = table.AddRow
sortedwidgetList = sorted(widgetList.values(),
key=lambda widget: widget.question.posn)
for widget in sortedwidgetList:
line = widget.writeToRTF(ss, langDict)
try:
AddRow(*line)
except:
if DEBUG:
raise
pass
section.append(table)
renderer = Renderer()
renderer.Write(doc, output)
return output
# -----------------------------------------------------------------------------
def series_export_spreadsheet(matrix, matrixAnswers, logo):
"""
Now take the matrix data type and generate a spreadsheet from it
"""
try:
import xlwt
except ImportError:
response.error = T("xlwt not installed, so cannot export as a Spreadsheet")
output = s3_rest_controller(module, "survey_series",
rheader=s3db.survey_series_rheader)
return output
import math
# -------------------------------------------------------------------------
def wrapText(sheet, cell, style):
row = cell.row
col = cell.col
try:
text = unicode(cell.text)
except:
text = cell.text
width = 16
# Wrap text and calculate the row width and height
characters_in_cell = float(width-2)
twips_per_row = 255 #default row height for 10 point font
if cell.merged():
try:
sheet.write_merge(cell.row,
cell.row + cell.mergeV,
cell.col,
cell.col + cell.mergeH,
text,
style
)
except Exception as msg:
log = current.log
log.error(msg)
log.debug("row: %s + vert: %s, col: %s + horiz %s" % \
(cell.row, cell.mergeV, cell.col, cell.mergeH))
posn = "%s,%s" % (cell.row, cell.col)
if matrix.matrix[posn]:
log.debug(matrix.matrix[posn])
rows = math.ceil((len(text) / characters_in_cell) / (1 + cell.mergeH))
else:
sheet.write(cell.row,
cell.col,
text,
style
)
rows = math.ceil(len(text) / characters_in_cell)
new_row_height = int(rows * twips_per_row)
new_col_width = width * COL_WIDTH_MULTIPLIER
if sheet.row(row).height < new_row_height:
sheet.row(row).height = new_row_height
if sheet.col(col).width < new_col_width:
sheet.col(col).width = new_col_width
# -------------------------------------------------------------------------
def mergeStyles(listTemplate, styleList):
"""
Take a list of styles and return a single style object with
all the differences from a newly created object added to the
resultant style.
"""
if len(styleList) == 0:
finalStyle = xlwt.XFStyle()
elif len(styleList) == 1:
finalStyle = listTemplate[styleList[0]]
else:
zeroStyle = xlwt.XFStyle()
finalStyle = xlwt.XFStyle()
for i in range(0, len(styleList)):
finalStyle = mergeObjectDiff(finalStyle,
listTemplate[styleList[i]],
zeroStyle)
return finalStyle
# -------------------------------------------------------------------------
def mergeObjectDiff(baseObj, newObj, zeroObj):
"""
function to copy all the elements in newObj that are different from
the zeroObj and place them in the baseObj
"""
elementList = newObj.__dict__
for (element, value) in elementList.items():
try:
baseObj.__dict__[element] = mergeObjectDiff(baseObj.__dict__[element],
value,
zeroObj.__dict__[element])
except:
if zeroObj.__dict__[element] != value:
baseObj.__dict__[element] = value
return baseObj
COL_WIDTH_MULTIPLIER = 240
book = xlwt.Workbook(encoding="utf-8")
output = StringIO()
protection = xlwt.Protection()
protection.cell_locked = 1
noProtection = xlwt.Protection()
noProtection.cell_locked = 0
borders = xlwt.Borders()
borders.left = xlwt.Borders.DOTTED
borders.right = xlwt.Borders.DOTTED
borders.top = xlwt.Borders.DOTTED
borders.bottom = xlwt.Borders.DOTTED
borderT1 = xlwt.Borders()
borderT1.top = xlwt.Borders.THIN
borderT2 = xlwt.Borders()
borderT2.top = xlwt.Borders.MEDIUM
borderL1 = xlwt.Borders()
borderL1.left = xlwt.Borders.THIN
borderL2 = xlwt.Borders()
borderL2.left = xlwt.Borders.MEDIUM
borderR1 = xlwt.Borders()
borderR1.right = xlwt.Borders.THIN
borderR2 = xlwt.Borders()
borderR2.right = xlwt.Borders.MEDIUM
borderB1 = xlwt.Borders()
borderB1.bottom = xlwt.Borders.THIN
borderB2 = xlwt.Borders()
borderB2.bottom = xlwt.Borders.MEDIUM
alignBase = xlwt.Alignment()
alignBase.horz = xlwt.Alignment.HORZ_LEFT
alignBase.vert = xlwt.Alignment.VERT_TOP
alignWrap = xlwt.Alignment()
alignWrap.horz = xlwt.Alignment.HORZ_LEFT
alignWrap.vert = xlwt.Alignment.VERT_TOP
alignWrap.wrap = xlwt.Alignment.WRAP_AT_RIGHT
shadedFill = xlwt.Pattern()
shadedFill.pattern = xlwt.Pattern.SOLID_PATTERN
shadedFill.pattern_fore_colour = 0x16 # 25% Grey
shadedFill.pattern_back_colour = 0x08 # Black
headingFill = xlwt.Pattern()
headingFill.pattern = xlwt.Pattern.SOLID_PATTERN
headingFill.pattern_fore_colour = 0x1F # ice_blue
headingFill.pattern_back_colour = 0x08 # Black
styleTitle = xlwt.XFStyle()
styleTitle.font.height = 0x0140 # 320 twips, 16 points
styleTitle.font.bold = True
styleTitle.alignment = alignBase
styleHeader = xlwt.XFStyle()
styleHeader.font.height = 0x00F0 # 240 twips, 12 points
styleHeader.font.bold = True
styleHeader.alignment = alignBase
styleSubHeader = xlwt.XFStyle()
styleSubHeader.font.bold = True
styleSubHeader.alignment = alignWrap
styleSectionHeading = xlwt.XFStyle()
styleSectionHeading.font.bold = True
styleSectionHeading.alignment = alignWrap
styleSectionHeading.pattern = headingFill
styleHint = xlwt.XFStyle()
styleHint.protection = protection
styleHint.font.height = 160 # 160 twips, 8 points
styleHint.font.italic = True
styleHint.alignment = alignWrap
styleText = xlwt.XFStyle()
styleText.protection = protection
styleText.alignment = alignWrap
styleInstructions = xlwt.XFStyle()
styleInstructions.font.height = 0x00B4 # 180 twips, 9 points
styleInstructions.font.italic = True
styleInstructions.protection = protection
styleInstructions.alignment = alignWrap
styleBox = xlwt.XFStyle()
styleBox.borders = borders
styleBox.protection = noProtection
styleInput = xlwt.XFStyle()
styleInput.borders = borders
styleInput.protection = noProtection
styleInput.pattern = shadedFill
boxL1 = xlwt.XFStyle()
boxL1.borders = borderL1
boxL2 = xlwt.XFStyle()
boxL2.borders = borderL2
boxT1 = xlwt.XFStyle()
boxT1.borders = borderT1
boxT2 = xlwt.XFStyle()
boxT2.borders = borderT2
boxR1 = xlwt.XFStyle()
boxR1.borders = borderR1
boxR2 = xlwt.XFStyle()
boxR2.borders = borderR2
boxB1 = xlwt.XFStyle()
boxB1.borders = borderB1
boxB2 = xlwt.XFStyle()
boxB2.borders = borderB2
styleList = {}
styleList["styleTitle"] = styleTitle
styleList["styleHeader"] = styleHeader
styleList["styleSubHeader"] = styleSubHeader
styleList["styleSectionHeading"] = styleSectionHeading
styleList["styleHint"] = styleHint
styleList["styleText"] = styleText
styleList["styleInstructions"] = styleInstructions
styleList["styleInput"] = styleInput
styleList["boxL1"] = boxL1
styleList["boxL2"] = boxL2
styleList["boxT1"] = boxT1
styleList["boxT2"] = boxT2
styleList["boxR1"] = boxR1
styleList["boxR2"] = boxR2
styleList["boxB1"] = boxB1
styleList["boxB2"] = boxB2
sheet1 = book.add_sheet(T("Assessment"))
sheetA = book.add_sheet(T("Metadata"))
maxCol = 0
for cell in matrix.matrix.values():
if cell.col + cell.mergeH > 255:
current.log.warning("Cell (%s,%s) - (%s,%s) ignored" % \
(cell.col, cell.row, cell.col + cell.mergeH, cell.row + cell.mergeV))
continue
if cell.col + cell.mergeH > maxCol:
maxCol = cell.col + cell.mergeH
if cell.joined():
continue
style = mergeStyles(styleList, cell.styleList)
if (style.alignment.wrap == style.alignment.WRAP_AT_RIGHT):
# get all the styles from the joined cells
# and merge these styles in.
joinedStyles = matrix.joinedElementStyles(cell)
joinedStyle = mergeStyles(styleList, joinedStyles)
try:
wrapText(sheet1, cell, joinedStyle)
except:
pass
else:
if cell.merged():
# get all the styles from the joined cells
# and merge these styles in.
joinedStyles = matrix.joinedElementStyles(cell)
joinedStyle = mergeStyles(styleList, joinedStyles)
try:
sheet1.write_merge(cell.row,
cell.row + cell.mergeV,
cell.col,
cell.col + cell.mergeH,
unicode(cell.text),
joinedStyle
)
except Exception as msg:
log = current.log
log.error(msg)
log.debug("row: %s + vert: %s, col: %s + horiz %s" % \
(cell.row, cell.mergeV, cell.col, cell.mergeH))
posn = "%s,%s" % (cell.row, cell.col)
if matrix.matrix[posn]:
log.debug(matrix.matrix[posn])
else:
sheet1.write(cell.row,
cell.col,
unicode(cell.text),
style
)
cellWidth = 480 # approximately 2 characters
if maxCol > 255:
maxCol = 255
for col in range(maxCol + 1):
sheet1.col(col).width = cellWidth
sheetA.write(0, 0, "Question Code")
sheetA.write(0, 1, "Response Count")
sheetA.write(0, 2, "Values")
sheetA.write(0, 3, "Cell Address")
for cell in matrixAnswers.matrix.values():
style = mergeStyles(styleList, cell.styleList)
sheetA.write(cell.row,
cell.col,
unicode(cell.text),
style
)
if logo != None:
sheet1.insert_bitmap(logo, 0, 0)
sheet1.protect = True
sheetA.protect = True
for i in range(26):
sheetA.col(i).width = 0