我试图在python-docx(https://github.com/mikemaccana/python-docx)的帮助下自动创建.docx文件(WordML ).我当前的脚本使用以下循环手动创建ToC:
for chapter in myChapters:
body.append(paragraph(chapter.text, style='ListNumber'))
Run Code Online (Sandbox Code Playgroud)
有没有人知道使用"内置单词"ToC功能的方法,它会自动添加索引并创建各个章节的段落链接?
非常感谢!
我在更新由 Linux 上的python-docx生成的 docx 文件中的目录时遇到问题。一般来说,创建TOC并不难(感谢这个答案/sf/answers/3403559211/和这个线程https://github.com/python-openxml/python-docx/issues/36)
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
paragraph = self.document.add_paragraph()
run = paragraph.add_run()
fldChar = OxmlElement('w:fldChar') # creates a new element
fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve') # sets attribute on element
instrText.text = 'TOC \o "1-3" \h \z \u' # change 1-3 depending on heading levels you need
fldChar2 = OxmlElement('w:fldChar')
fldChar2.set(qn('w:fldCharType'), 'separate')
fldChar3 = OxmlElement('w:t')
fldChar3.text = "Right-click …Run Code Online (Sandbox Code Playgroud)