打开Word文档。
按下 Alt + F11 打开VBA编辑器。
在VBA编辑器中,选择 插入 > 模块,然后粘贴以下代码:
Sub FormatPics()
Dim Shap As InlineShape
For Each Shap In ActiveDocument.InlineShapes
If Shap.Type = wdInlineShapePicture Then
Shap.LockAspectRatio = msoFalse
Shap.Height = CentimetersToPoints(7.4)
Shap.Width = CentimetersToPoints(15.15)
End If
Next
End Sub
运行脚本:在VBA编辑器中,按 F5 或选择 运行 来执行这个宏。
python代码给图片插入编号(针对车跑出的图片)
from docx import Document
from docx.oxml import OxmlElement
文件路径
file_path = r"D:\Desktop\xxx.docx"
打开 Word 文件
doc = Document(file_path)
初始化图片编号
image_base = 3 # 编号基数
image_number = 1
遍历文档中的所有段落
for paragraph in doc.paragraphs:
for run in paragraph.runs:
# 检测运行中是否包含图片
if “w:drawing” in run._element.xml:
# 计算图例编号
legend_number = f"{image_base}.{image_number}"
# 创建一个新的运行对象用于图例
legend_run = OxmlElement("w:r")
legend_text = OxmlElement("w:t")
legend_text.text = f" 图 {legend_number}" # 设置图例文本
image_number += 1
# 将图例文本嵌入到运行中
legend_run.append(legend_text)
run._element.addnext(legend_run) # 在当前运行对象之后插入图例运行
保存修改后的文件
output_path = file_path.replace(“.docx”, “_带图例.docx”)
doc.save(output_path)
print(f"已完成,文件保存为:{output_path}")