python-docx-template icon indicating copy to clipboard operation
python-docx-template copied to clipboard

Use the for loop to traverse the word document with blank lines

Open xrl12 opened this issue 2 years ago • 3 comments

My Word Document

image

My code

from docxtpl import DocxTemplate

# import docxtpl

test_data = [
    {"id": "1", "name": "alex_1", "age": 13, "sex": "男"},
    {"id": "1", "name": "alex_2", "age": 15, "sex": "男"},
    {"id": "1", "name": "alex_3", "age": 17, "sex": "男"},
    {"id": "1", "name": "alex_4", "age": 19, "sex": "男"},
    {"id": "1", "name": "alex_5", "age": 21, "sex": "男"},
]


def createDoc(contexts):
    """
    :param contexts: 生成文件的内容
    :return: 生成文件
    """
    doc = DocxTemplate("./test.docx")
    doc.render(
        {
            "title": "hello world",
            "couse_list": ["课程一", "课程二", "课程三"],
            "couse_name": "语文",
            "couse_id": "1",
            "table_col": ["表头1", "表头2", "表头三"],
            "table_data": [
                {
                    "number": "章节1",
                    "col_content": ["1-1", "1-2", "1-3"]
                },
                {
                    "number": "章节2",
                    "col_content": ["2-1", "2-2", "2-3"]
                }
            ]
        }
    )
    doc.save('aaa.docx')


if __name__ == '__main__':
    createDoc(test_data)

result

image

xrl12 avatar Oct 25 '22 09:10 xrl12

Well, what is wrong?

SergeyZaykov avatar Nov 13 '22 22:11 SergeyZaykov

{% for xxx%} 和 {% endfor %} 分别改为 {%tr for xxx%} 和 {%tr endfor %}

houjieyi avatar Feb 22 '24 03:02 houjieyi

{% for xxx%} 和 {% endfor %} 分别改为 {%tr for xxx%} 和 {%tr endfor %}

It didn't help. The row of merged columns does not extend to all the table width.

nested_horizontal_merge_tpl-1.docx generated_doc.docx

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


"""Testing the nested_horizontal_merge_tpl.docx template."""

from docxtpl import DocxTemplate

doc = DocxTemplate("nested_horizontal_merge_tpl-1.docx")
doc.render({})
doc.save("generated_doc.docx")

Python 3.10.13 docxtpl 0.16.5 python-docx 1.1.0

SergeyZaykov avatar Feb 22 '24 08:02 SergeyZaykov