我创建了一个 docx 模板,然后使用 python 的 docxtpl 包生成了 python 代码以将变量和所有其他数据更新到该模板中:
tpl = DocxTemplate((path.join('report','templates','my_template.docx')))
tpl.new_subdoc()
file_path = path.join(output_dir_name, file_name)
get_all_data_report(tpl)
tpl.save(file_path)enter code here
我不明白如何才能完全控制生成的 docx 文件中的空格/分页符。 如果我在页面开头的模板中放置一些文本,它有时会移动并添加 x 行间距。
请您参考如下方法:
from docxtpl import *
tpl = DocxTemplate('templates/escape_tpl.docx')
context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'),
'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ',
'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'),
'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break'),
'page_break': R('\f'),
}
tpl.render(context)
tpl.save('output/escape.docx')
并在模板中使用 {{r page_break}}
看这个 https://github.com/elapouya/python-docx-template/blob/master/tests/escape.py
还有这个 https://github.com/elapouya/python-docx-template/blob/master/tests/templates/escape_tpl.docx
