python-docx 目录、页码 (更新页码要通过软件)

添加目录

import hashlib
import re

import docx.document
from docx.oxml import parse_xml
from docx.text.paragraph import Paragraph


def table_of_contents(doc: docx.document.Document):
    doc.add_heading("目录")
    r = doc.add_paragraph().add_run()
    return r.element


def add_heading(doc: docx.document.Document, title: str, ml):
    w_id = int(re.findall(r'^(\d+)\.', title)[0])
    bookmark = '_Toc' + hashlib.md5(title.encode('utf-8')).hexdigest()[:4]
    template = f"""<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
        <w:pPr><w:pstyle w:val="Heading1"></w:pstyle></w:pPr>
        <w:bookmarkStart w:id="{w_id}" w:name="{bookmark}"/>
        <w:r><w:t>{title}</w:t></w:r>
        <w:bookmarkEnd w:id="{w_id}"/></w:p>
    """
    p = parse_xml(template)
    doc.element.body.insert_element_before(p, 'w:sectPr')
    p = Paragraph(p, doc._body)
    p.style = "Heading 1"
    ml.append(table_of_content(title, 1, bookmark))


def table_of_content(s_title, page_num, bookmark='_Toc15376'):
    template = f"""<w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
        <w:pPr><w:pStyle w:val="26"/><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="8309"/></w:tabs></w:pPr>
        <w:r><w:fldChar w:fldCharType="begin"/></w:r>
        <w:r><w:instrText xml:space="preserve"> HYPERLINK \\l {bookmark} </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="separate"/></w:r>
        <w:r><w:t>{s_title}</w:t></w:r>
        <w:r><w:tab/></w:r>
        <w:r><w:fldChar w:fldCharType="begin"/></w:r>
        <w:r><w:instrText xml:space="preserve"> PAGEREF {bookmark} \\h </w:instrText></w:r>
        <w:r><w:fldChar w:fldCharType="separate"/></w:r>
        <w:r><w:t>{page_num}</w:t></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r>
        <w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>
    """
    return parse_xml(template)


doc = docx.Document()
ml = table_of_contents(doc)

add_heading(doc, "1.Test1", ml)
add_heading(doc, "2.Test2", ml)
add_heading(doc, "3.Test3", ml)
add_heading(doc, "4.Test4", ml)
add_heading(doc, "5.Test5", ml)

doc.save('test.docx')

添加页码

 docx文件本质是个zip压缩包

使用word编辑好的页脚,解压、替换对应的footer1.xml文件就可以了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用`python-docx`库给Word文件设置页码,您可以使用`docx`库中的`Document`对象的相关方法和属性。以下是一个示例代码: ```python from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Pt def set_page_number(filename): # 打开Word文档 doc = Document(filename) # 获取文档的默认节 default_section = doc.sections[0] # 设置页码在页脚居中显示 default_section.footer.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 添加页码段落 page_number_paragraph = default_section.footer.paragraphs[0].add_run() # 设置页码字体样式和大小 page_number_font = page_number_paragraph.font page_number_font.size = Pt(12) page_number_font.name = 'Arial' # 遍历文档的每个节 for section in doc.sections: # 获取当前节的页脚段落 footer_paragraph = section.footer.paragraphs[0] # 添加页码字段 page_number_field = footer_paragraph.add_field('PAGE') # 保存修改后的文档 doc.save("modified.docx") print("页码已设置成功!") # 调用函数并传入要处理的Word文件名 set_page_number("example.docx") ``` 请确保在运行代码之前安装了`python-docx`库,可以使用以下命令进行安装:`pip install python-docx`。 上述代码将打开指定的Word文件,并设置页码在页脚居中显示。然后,通过添加页码字段来为每个节的页脚添加页码。您可以根据需要自定义页码的样式,例如字体、大小和对齐方式等。最后,将修改后的文档保存为"modified.docx"。 请注意,此示例将在每个节的页脚添加页码字段,因此整个文档的页码将保持连续。如果您需要在特定节之后重新开始页码,请参考`python-docx`库的官方文档,了解如何使用`docx.enum.section.WD_SECTION_START`属性来设置节的起始页码。 希望这可以帮助您设置Word文件的页码。如有需要,请自行调整代码以满足特定需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值