Iterating through a table importing images

ぃ、小莉子 提交于 2020-01-25 07:28:27

问题


Importing images using Python docx. Found some help from old post but unable to convert it to a 3 row, 2 col 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')

I've adapted it to...

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')

回答1:


You're adding too many rows. You should have all the rows you need after the table is created. Access a row using table.rows[i] where i is in (0, 1, 2).

So something like:

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')


来源:https://stackoverflow.com/questions/59146558/iterating-through-a-table-importing-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!