以编程方式添加行号

2024-05-02 14:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够以编程方式将行号添加到整个文档中。我偶然发现了python-docx,它允许我在python中处理.docx文件。但是,我无法使用以下代码成功地使用扩展名将行号添加到文档中:

from docx import Document
from docx.oxml.shared import OxmlElement

document = Document('sample.docx')

sections = document.sections

for section in sections:
    sectPr = section._sectPr

    lnNumType = OxmlElement('w:lnNumType')
    lnNumType.set('countBy', '1')
    lnNumType.set('start', '1')
    lnNumType.set('restart', 'newSection')
    sectPr.append(lnNumType)

document.save('sample-output.docx')

当我在Word中打开生成的sample-output.docx时,行号不会显示出来。然而,当我将文件转换为xml时,我可以看到<w:lnNumType w:count-by="5" w:distance="282.9954" w:restart="continuous"/>已经添加到文档中。在<w:wordDocument><w:body>xml标记中。你知道吗

我不太确定这是我的代码的问题还是.docx的工作方式导致的问题。你知道吗


Tags: 文件sample代码from文档import方式document