小编Alg*_*n70的帖子

python-docx 将图片放入表格时出现问题

我正在使用 python-docx 创建一个新文档,然后添加一个表(行=1,列=5)。然后我向五个单元格中的每一个添加一张图片。我的代码可以运行,但我从 docx 中看到的内容与我手动使用 Word 时看到的内容不同。

具体来说,如果我设置“显示格式标记”,然后查看 docx 生成的内容,则每个单元格的开头总是有一个硬回车(通过 add_paragraph 方法放置在那里)。当我手动使用 Word 时,没有硬性回报。

硬返回的结果是每张图片都比我想要的位置下降了一行。如果我使用 Word,图片就会出现在我期望的位置。

另外奇怪的是,在docx文档上我可以手动进去单击硬回车旁边,按一次下光标键,然后按一次退格键,硬回车被删除,图片移动到细胞的顶部。

所以我的问题是,有谁知道如何在执行 add_paragraph 方法时在表格单元格中获取图片而不需要硬返回?

任何帮助将不胜感激。

def paragraph_format_run(cell):
    paragraph = cell.add_paragraph()
    format = paragraph.paragraph_format
    run = paragraph.add_run()
    
    format.space_before = Pt(0)
    format.space_after = Pt(0)
    format.line_spacing = 1.0
    format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    return paragraph, format, run

def main():
    document = Document()
    
    sections = document.sections
    section = sections[0]
    
    section.top_margin = Inches(1.0)
    section.bottom_margin = Inches(1.0)
    section.left_margin = Inches(0.75)
    section.right_margin = Inches(0.75)
    
    table = document.add_table(rows=1, cols=5)
    table.allow_autofit = False
    
    cells = …
Run Code Online (Sandbox Code Playgroud)

python python-docx

3
推荐指数
1
解决办法
4834
查看次数

标签 统计

python ×1

python-docx ×1