合并多個Word文檔
# 合并多個Word文檔為一個
def merge_documents(output_file, *input_files):
merged_doc = Document()
for file in input_files:
sub_doc = Document(file)
for element in sub_doc.element.body:
merged_doc.element.body.append(element)
merged_doc.save(output_file)
merge_documents('merged_example.docx', 'doc1.docx', 'doc2.docx')
print("多個文檔已成功合并!")
解釋
該腳本將多個Word文檔合并為一個新文檔。這在需要匯總不同來源的報告時特別有用,可以減少繁瑣的復制粘貼過程。
插入圖片
# 在文檔中插入圖片
def insert_image_into_document(file_name, image_path):
doc = Document(file_name)
doc.add_picture(image_path, width=None) # 可以設置width參數
doc.save(file_name)
insert_image_into_document('example.docx', 'image.png')
print("圖片已成功插入文檔中!")
解釋
這個腳本將指定的圖片插入到Word文檔中。在撰寫報告或制作演示文稿時,圖像可以有效增強信息傳達,使用這個功能可以快速豐富文檔內容。