python 批量修改word文档页眉页脚
from docx import Documentfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt
from docx.shared import Inches
import os
doc = Document('test.docx')
def update_header_footer(doc, header_logo, footer_text, save_file_name):
section = doc.sections
header = section.header
header_paragraph = header.paragraphs
# 这里既可以添加图片也可以添加文字
run = header_paragraph.add_run()
logo_path = header_logo
run.add_picture(logo_path, width=Inches(1))
# 这里是添加文字的代码
# header_paragraph.text = "这里是页眉"
# header_paragraph.style.font.size = Pt(12)
header_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
footer = section.footer
footer_paragraph = footer.paragraphs
footer_paragraph.text = footer_text
footer_paragraph.style.font.size = Pt(12)
footer_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 访问并修改页眉
# header = doc.sections.header
# header.paragraphs.text = '新的页眉内容'
# footer = doc.sections.footer
# footer.paragraphs.text = '新的页脚内容'
# header_paragraph = doc.sections.header.paragraphs
# run = header_paragraph.add_run()
# logo_path = './imgs/image1_37419.png'
# run.add_picture(logo_path, width=Inches(1))
doc.save(save_file_name)
def update_all_doc(directory, header_logo, footer_text):
os.makedirs(save_dirs, exist_ok=True)
for filename in os.listdir('./'):
try:
if filename.endswith('.docx'):
# doc_path = filename
doc_path = filename
print(doc_path)
doc = Document(doc_path)
save_file_name = os.path.join(save_dirs, filename)
update_header_footer(
doc, header_logo, footer_text, save_file_name)
except:
continue
if __name__ == "__main__":
directory = "outputdoc"
header_logo = "./imgs/image1_37419.png"
footer_text = '© 2024 Honoreal. All rights reserved.'
save_dirs = "add header and footer"
update_all_doc(directory, header_logo, footer_text) 虽然不知道有啥用,但还是支持原创! 虽然知道怎么用,但用不到 感觉很有用的感觉 虽然不知道有啥用,但还是支持原创!感觉很有用 文档样式要是能指定就好了 支持原创!! 不知道有啥用的我来说:搞论文的大学生~ 有没有高大上感觉 学习学习
页:
[1]
2