import os
import win32com.client
from win32com.client import constants
def batch_set_margins(folder_path, top=2.54, bottom=2.54, left=3.17, right=3.17, unit='cm', file_extensions=('.doc', '.docx')):
"""
批量修改指定文件夹下所有Word文档的页边距
参数:
folder_path: 包含Word文档的文件夹路径
top: 上边距
bottom: 下边距
left: 左边距
right: 右边距
unit: 单位 ('cm' 或 'inch')
file_extensions: 要处理的文件扩展名元组
"""
# 转换单位为磅(Word内部使用磅为单位)
if unit == 'cm':
factor = 28.35 # 1厘米 = 28.35磅
elif unit == 'inch':
factor = 72 # 1英寸 = 72磅
else:
raise ValueError("单位必须是 'cm' 或 'inch'")
top_pt = top * factor
bottom_pt = bottom * factor
left_pt = left * factor
right_pt = right * factor
# 获取所有Word文档
doc_files = []
for ext in file_extensions:
doc_files.extend([f for f in os.listdir(folder_path) if f.lower().endswith(ext)])
if not doc_files:
print(f"在 {folder_path} 中没有找到Word文档")
return
# 启动Word应用程序
word = win32com.client.Dispatch("Word.Application")
word.Visible = False # 不显示Word界面
word.DisplayAlerts = False # 不显示警告
success_count = 0
fail_count = 0
for doc_file in doc_files:
file_path = os.path.join(folder_path, doc_file)
doc = None
try:
print(f"正在处理: {doc_file}")
doc = word.Documents.Open(file_path)
# 修改每一节的页边距
for section in doc.Sections:
section.PageSetup.TopMargin = top_pt
section.PageSetup.BottomMargin = bottom_pt
section.PageSetup.LeftMargin = left_pt
section.PageSetup.RightMargin = right_pt
# 保存并关闭
doc.Save()
doc.Close()
success_count += 1
print(f"✓ {doc_file} 修改成功")
except Exception as e:
fail_count += 1
print(f"✗ {doc_file} 修改失败: {str(e)}")
if doc:
try:
doc.Close(False) # 不保存关闭
except:
pass
# 退出Word应用程序
word.Quit()
print(f"\n处理完成!成功: {success_count} 个, 失败: {fail_count} 个")
# 使用示例
if __name__ == "__main__":
# 设置要处理的文件夹路径(请根据实际情况修改)
folder_path = r"C:\Users\YourName\Documents\WordFiles"
# 设置页边距(单位:厘米)
# 标准A4纸默认边距:上下2.54cm,左右3.17cm
# 可以根据需要修改这些数值
batch_set_margins(
folder_path=folder_path,
top=2.54, # 上边距(厘米)
bottom=2.54, # 下边距(厘米)
left=3.17, # 左边距(厘米)
right=3.17, # 右边距(厘米)
unit='cm' # 单位:厘米
)
# 或者使用英寸
# batch_set_margins(
# folder_path=folder_path,
# top=1.0, # 上边距(英寸)
# bottom=1.0, # 下边距(英寸)
# left=1.25, # 左边距(英寸)
# right=1.25, # 右边距(英寸)
# unit='inch' # 单位:英寸
# )
使用说明
安装依赖
首先需要安装pywin32库:

pip install pywin32
使用方法
-
修改文件夹路径:将
folder_path变量设置为包含Word文档的文件夹路径 -
设置页边距:根据需要修改
top、bottom、left、right参数的值(单位默认为厘米) -
运行脚本:直接运行Python脚本即可
注意事项
-
需要安装Microsoft Word:此脚本依赖于Windows系统的Word应用程序
-
文件备份:建议先备份重要文档,或先在测试文件夹中运行
-
Word版本:适用于Word 2007及以上版本(.docx格式),对.doc格式也有较好支持
-
运行速度:处理大量文档时需要一些时间,脚本会显示处理进度
-
错误处理:脚本会捕获并显示处理过程中的错误,例如文件被占用或损坏等情况
常见问题
- COM错误:确保Word已正确安装且没有正在运行的其他Word进程
- 权限问题:确保对目标文件夹有读写权限
- 文件格式:默认处理.doc和.docx文件,可以通过
file_extensions参数修改
这个脚本提供了批量修改Word文档页边距的便捷方式,可以大大提高工作效率。