python-docxのtable内にtableを配置する

Microsoft Wordの文章で、表に中のセルに更に表を埋め込む場合があると思います。

from docx import Document
from docx.shared import Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.section import WD_ORIENT

doc = Document()
section = doc.sections[-1]
new_width, new_height = section.page_height, section.page_width
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width = new_width
section.page_height = new_height

table = doc.add_table(3, 3, style='Table Grid')
j = 0
for row in table.rows:
    for cell in row.cells:
        if j == 4:
            tbl_in_tbl = cell.add_table(3, 3)
            k = 0
            for mini_row in tbl_in_tbl.rows:
                for mini_cell in mini_row.cells:
                    p = mini_cell.add_paragraph()
                    p.alignment=WD_ALIGN_PARAGRAPH.CENTER
                    r = p.add_run()
                    s = str(k+11) + ".jpg"
                    r.add_picture(s, width=Cm(1.5), height=Cm(1))
                    k += 1
        else:
            p = cell.add_paragraph()
            p.alignment=WD_ALIGN_PARAGRAPH.CENTER
            r = p.add_run()
            s = str(j+1) + ".jpg"
            r.add_picture(s, width=Cm(5), height=Cm(4))
        j += 1

doc.save("test.docx")

手元の環境では、セル内に表示したtableに対するstyleは設定できませんでした。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA