from docxtpl import DocxTemplate, InlineImage
from docx.shared import Inches, Cm, Mm
import jinja2
word_template = 'tpl.docx'
out_word_file = 'new_test.docx'
input_file = "input.txt"
image_dir = '/mnt/f/'
desc_string = f"""
desc_string
"""
tpl = DocxTemplate(word_template)
with open(input_file) as f_in:
data_list = [i.split('\t') for i in f_in.read().strip('\n').split('\n')]
frameworks = []
for line_list in data_list[1:]:
sample, sample_area, target_area, score = line_list
image_path_1 = f"{image_dir}/{sample}_5.0x.jpg"
image_path_2 = f"{image_dir}/{sample}_20.0x.jpg"
sample_image_dict = {
'sample': sample,
'sample_area' : sample_area,
'target_area' : target_area,
'score' : score,
'image_1': InlineImage(tpl, image_path_1, width=Mm(76), height=Mm(40)),
'image_2': InlineImage(tpl, image_path_2, width=Mm(76), height=Mm(40)),
}
frameworks.append(sample_image_dict)
context = {
'frameworks': frameworks
}
jinja_env = jinja2.Environment(autoescape=True)
tpl.render(context, jinja_env)
tpl.save(out_word_file)
print(out_word_file)
复制出代码
{%tr for items in frameworks %}
{{ items.image_1 }} {{ items.image_2 }}
{{ items.sample }}
样本评分:{{ items.score }} 样本面积:{{ items.sample_area }} 目标面积:{{ items.target_area }}
{%tr endfor %}
名称 样本面积 目标面积 样本评分
A 10 5 0.5
链接: https://github.com/elapouya/python-docx-template
https://zhuanlan.zhihu.com/p/146363527