Merge pull request #93 from Arthaslixin/master

Add vertical cell merge support in a loop
This commit is contained in:
Eric Lapouyade 2017-10-15 11:41:18 +02:00 committed by GitHub
commit 41671a0363
4 changed files with 34 additions and 1 deletions

View File

@ -85,7 +85,17 @@ class DocxTemplate(object):
# This is mandatory to have jinja2 generating correct xml code
pat = r'<w:%(y)s[ >](?:(?!<w:%(y)s[ >]).)*({%%|{{)%(y)s ([^}%%]*(?:%%}|}})).*?</w:%(y)s>' % {'y':y}
src_xml = re.sub(pat, r'\1 \2',src_xml,flags=re.DOTALL)
# add vMerge
# use {% vm %} to make this table cell and its copies be vertically merged within a {% for %}
pat_vm = r'(<\/w:tcPr>.*)(<\/w:tcPr>)(.*?){%vm%}.*?<w:t>(.*?)(<\/w:t>)'
def vMerge(m):
return m.group(1) + '<w:vMerge {% if loop.first %}w:val="restart"{% endif %}/>' + m.group(2) + m.group(3) + "{% if loop.first %}"+ m.group(4) +"{% endif %}" + m.group(5)
pat_num_vm = re.compile(r'{%vm%}')
num = len(pat_num_vm.findall(src_xml))
for i in range(0,num):
src_xml = re.sub(pat_vm,vMerge,src_xml)
def clean_tags(m):
return m.group(0).replace(r"&#8216;","'").replace('&lt;','<').replace('&gt;','>')
src_xml = re.sub(r'(?<=\{[\{%])(.*?)(?=[\}%]})',clean_tags,src_xml)

Binary file not shown.

Binary file not shown.

23
tests/vertical merge.py Normal file
View File

@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
'''
Created : 2017-10-15
@author: Arthaslixin
'''
from docxtpl import DocxTemplate
tpl=DocxTemplate('test_files/vertical_merge_tpl.docx')
context = {
'items' : [
{'desc' : 'Python interpreters', 'qty' : 2, 'price' : 'FREE' },
{'desc' : 'Django projects', 'qty' : 5403, 'price' : 'FREE' },
{'desc' : 'Guido', 'qty' : 1, 'price' : '100,000,000.00' },
],
'total_price' : '100,000,000.00',
'category' : 'Book'
}
tpl.render(context)
tpl.save('test_files/vertical_merge.docx')