我在一家向不同客户发送文件的公司工作。我们从不同的供应商那里收到这些数据,他们根据他们的公司对它们进行格式化。在发送之前我必须确保它们都是相同的格式。
为此,我正在尝试创建一个程序,可以搜索文件夹中的所有word文档,将字体大小更改为13,将字体更改为garamond
使用下面的代码我只能改变字体大小。我哪里错了?
import os
from docx import Document
from docx.shared import Pt
def get_paragraph_runs(paragraph):
return [run for run in paragraph.runs]
def update_font_to_garamond(document):
for paragraph in document.paragraphs:
runs = get_paragraph_runs(paragraph)
for run in runs:
run.font.name = 'Garamond'
run.font.size = Pt(13)
def update_documents_in_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".docx"):
file_path = os.path.join(root, file)
document = Document(file_path)
update_font_to_garamond(document)
document.save(file_path)
print(f"Update complete for '{file_path}'.")
像这样修改你的
update_font_to_garamond
函数:
def update_font_to_garamond(document):
for paragraph in document.paragraphs:
paragraph.style.font.name = 'Garamond'
paragraph.style.font.size = Pt(13)
这样,您就可以更新整个段落的样式,包括其段落,而不仅仅是单独的段落。