You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用python-docx将图片插入到Word文档的最顶部

实现将Excel导出图片插入Word文档最顶部的正确方法

问题原因

你原有代码是在文档已有的第一个段落末尾追加Run对象插入图片,因此图片会出现在首段原有文本的下方,无法实现放到所有内容最顶部的效果。

解决方案

python-docx的Paragraph对象内置了insert_paragraph_before()方法,可以在当前段落之前插入新段落,我们只需要在原有第一个段落前插入空段落用来承载图片即可,修改后的代码如下:

from docx import Document
from docx.shared import Inches
import excel2img

# 导出Excel指定区域为本地图片
excel2img.export_img("test.xlsx","image2.png",  "Sheet1", "G13:J22")
    
document = Document('filename.docx')

# 定位原有文档的第一个段落
original_first_paragraph = document.paragraphs[0]
# 在原有首段之前插入新的空段落,作为图片的容器
new_top_paragraph = original_first_paragraph.insert_paragraph_before()

# 在新插入的顶部段落中添加图片
run = new_top_paragraph.add_run()
run.add_picture('image2.png', width=Inches(6.65), height=Inches(2.02))

document.save('new.docx')

补充说明

  • insert_paragraph_before()如果不传文本参数,会默认插入纯空段落,不会产生多余的文本内容
  • 如果你不希望图片和后续原有内容之间有空行,可以在插入图片后手动设置新段落的段后间距为0即可。

内容的提问来源于stack exchange,提问作者RandallCloud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 16:15:04