-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathend.py
More file actions
86 lines (72 loc) · 3.36 KB
/
Copy pathend.py
File metadata and controls
86 lines (72 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import json
from docx import Document
from docx.shared import Inches
import os
def load_ans_from_file(filename="ans.json"):
with open(filename, 'r', encoding='utf-8') as f:
return json.load(f)
def insert_sql_and_images(doc_path, ans):
# 打开现有的 Word 文档
doc = Document(doc_path)
# 遍历每一个任务(任务索引从 0 开始)
for task_index, task in enumerate(ans):
sql = task.get("sql", "") # 当前任务的 SQL 语句
before_imgs = task.get("before_img", []) # 前置图片路径列表
after_imgs = task.get("after_img", []) # 后置图片路径列表
# --------------------------
# 1. 替换 SQL 语句 [n-sql]
# --------------------------
for paragraph in doc.paragraphs:
if f"[{task_index}-sql]" in paragraph.text:
paragraph.clear()
new_run = paragraph.add_run()
new_run.text=sql #
# --------------------------
# 2. 插入前置图片 [n-img-before]
# --------------------------
for paragraph in doc.paragraphs:
# 检查段落中是否包含目标标识 ,因为 标识独占一个段落,所以可以直接清空 run
if f"[{task_index}-img-before]" in paragraph.text:
# 清空段落的所有 run
paragraph.clear()
# 插入前置图片到占位符的位置
for img in before_imgs:
try:
img_path = img
if os.path.exists(img_path):
# 在段落中插入新 run 用于图片
new_run = paragraph.add_run()
new_run.add_picture(img_path, width=Inches(4)) # 插入图片并设置宽度
else:
print(f"图片路径不存在:{img_path}")
except Exception as e:
print(f"插入前置图片失败(任务 {task_index},图片 {img}):{e}")
# # --------------------------
# # 3. 插入后置图片 [n-img-after]
# # --------------------------
for paragraph in doc.paragraphs:
if f"[{task_index}-img-after]" in paragraph.text:
paragraph.clear()
# 插入后置图片到占位符的位置
for img in after_imgs:
try:
# 检查图片路径是否存在
img_path=img
if os.path.exists(img_path):
run = paragraph.add_run() # 在当前段落中添加新的 Run
run.add_picture(img_path, width=Inches(4)) # 设置图片宽度为 4 英寸
else:
print(f"图片路径不存在:{img_path}")
except Exception as e:
print(f"插入后置图片失败(任务 {task_index},图片 {img}):{e}")
# 保存修改后的文档(不会覆盖原文件)
output_path = "./updated_report.docx"
doc.save(output_path)
print(f"报告已生成,保存为:{output_path}")
# 调用处理函数
def main():
# 读取 ans 列表
ans = load_ans_from_file("./ans.json")
insert_sql_and_images('./insert_test3.docx',ans)
if __name__=='__main__':
main()