from docx.oxml import OxmlElement, ns
#下面三个函数无脑复制粘贴
def create_element(name):
return OxmlElement(name)
def create_attribute(element, name, value):
element.set(ns.qn(name), value)
def add_page_number(run):
fldChar1 = create_element('w:fldChar')
create_attribute(fldChar1, 'w:fldCharType', 'begin')
instrText = create_element('w:instrText')
create_attribute(instrText, 'xml:space', 'preserve')
instrText.text = "PAGE"
fldChar2 = create_element('w:fldChar')
create_attribute(fldChar2, 'w:fldCharType', 'end')
run._r.append(fldChar1)
run._r.append(instrText)
run._r.append(fldChar2)
#没有要求的话,上面三个函数就不用去研究
#下面正文开始
doc = Document()
add_page_number(doc.sections[0].footer.paragraphs[0].add_run())
footer = doc.sections[0].footer # 获取页脚
paragraph = footer.paragraphs[0] # 获取页脚的第一个段落
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 设置页号居中
paragraph.runs[0].bold = True #设置字体粗体
paragraph.runs[0].font.size = Pt(15) #设置字号
doc.save("./docFile/test1.docx") #保存,路径自己选择
Python-docx为多页word填写连续页号
最新推荐文章于 2024-05-19 23:31:32 发布