python - 使用 python-docx 添加页码

标签 python ms-word python-docx

我正在尝试使用 python-docx 在 word 文档的页脚中添加页码。到目前为止,我还没有找到如何做到这一点。 This问题地址如何找到页码(或如何不能)。 This一个谈论创建模板并在那里添加页码。有没有办法在我使用 doc = Document() 创建的文档上添加页码?

最佳答案

感谢 Syafiqur__ 和 scanny,我想出了一个添加页码的解决方案。

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())
doc.save("your_doc.docx")

关于python - 使用 python-docx 添加页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56658872/

相关文章:

python - 在django中生成MS word文档

python - 用于在意大利 map 上呈现数据的 Bokeh

python - 预期出现缩进 block 错误 <python>

java - 将 jsp 表导出到 excel、word、pdf

coldfusion - 在Coldfusion中创建Word文档-如何进行页码编号?

Python docx row.cells 多次返回 "merged"单元格

python - 将坐标列表转换为一组列表/网格引用

python - heroku run python manage.py 如何迁移?

c# - 是否可以根据正在查看的文件结束 Microsoft Word 进程?

java - 创建一个 DOCX 从 Oracle 数据库读取数据