import
os
from
openpyxl
import
load_workbook
from
docx
import
Document
from
docx.shared
import
Inches
def
excel_images_to_word(excel_path, word_path, target_width_cm
=
15
):
temp_dir
=
"excel_temp_images"
os.makedirs(temp_dir, exist_ok
=
True
)
wb
=
load_workbook(excel_path)
img_counter
=
0
image_paths
=
[]
for
sheet
in
wb.worksheets:
for
img
in
sheet._images:
img_filename
=
f
"image_{img_counter}.png"
img_path
=
os.path.join(temp_dir, img_filename)
with
open
(img_path,
"wb"
) as f:
f.write(img._data())
image_paths.append(img_path)
img_counter
+
=
1
doc
=
Document()
target_width
=
Inches(target_width_cm
/
2.54
)
for
img_path
in
image_paths:
doc.add_picture(img_path, width
=
target_width)
doc.add_paragraph()
doc.save(word_path)
for
img_path
in
image_paths:
os.remove(img_path)
os.rmdir(temp_dir)
if
__name__
=
=
"__main__"
:
excel_file
=
"input.xlsx"
word_file
=
"output.docx"
excel_images_to_word(excel_file, word_file, target_width_cm
=
15
)
print
(f
"图片已成功导出到:{word_file}"
)