遍历 table 导入图像

Iterating through a table importing images

正在使用 Python docx 导入图像。从旧 post 找到了一些帮助,但无法将其转换为 3 行,2 列 table。

from docx import Document

document = Document()
tables = document.tables
table = document.add_table(rows=1, cols=2)
row_cells = table.add_row().cells

**for i, image in enumerate(['image1.jpg', 'image2.jpg']):
    paragraph = row_cells[i].paragraphs[0]**
    run = paragraph.add_run()
    run.add_picture(image)
document.save('doc.docx')

我已经将其改编为...

document = Document()
tables = document.tables

table = document.add_table(rows=3, cols=2)
table.style = 'Table Grid'
row_cells = table.add_row().cells

Inc1 = ['1.jpg', '2.jpg','1.jpg', '2.jpg','1.jpg', '2.jpg']
length =  len (Inc1)
for i in range(length):
for j in table.rows:
    for k in table.columns:
        paragraph = table.add_row().cells[i].paragraphs[0]
        run =  table.add_row().cells[i].paragraphs[0].paragraph.add_run()
        run.add_picture('1.jpg', width = Inches(1))

document.save('test.docx')

您添加的行太多。创建 table 后,您应该拥有所需的所有行。使用 table.rows[i] 访问一行,其中 i(0, 1, 2).

所以像这样:

document = Document()
table = document.add_table(rows=3, cols=2)

Inc1 = ['1.jpg', '2.jpg','1.jpg', '2.jpg','1.jpg', '2.jpg']

for irow in range(3):
    for icol in range(2):
        paragraph = table.rows[irow].cells[icol].paragraphs[0]
        run = paragraph.add_run()
        run.add_picture(Inc1[(irow*2)+icol], width=Inches(1))

document.save('test.docx')