我在Python中使用这两个函数为我的word文件创建目录。
def create_TOC(document, mystyle1):
add_paragraph_text(document, mystyle1, 'CENTER', True, 'Content of Doc'.decode('utf-8'), False, True)
paragraph = 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 = r'''TOC \o "1-4" \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 to update field."
fldChar2.append(fldChar3)
fldChar4 = OxmlElement('w:fldChar')
fldChar4.set(qn('w:fldCharType'), 'end')
run.font.rtl = True
r_element = run._r
r_element.append(fldChar)
r_element.append(instrText)
r_element.append(fldChar2)
r_element.append(fldChar4)
document.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
return [r_element, paragraph]
def update_TOC(r_element, paragraph):
updateFields=OxmlElement('w:updateFields')
updateFields.set(qn('w:val'), 'true')
r_element.append(updateFields)
p_element = paragraph._p
...emmited code
当我打开创建的Word文件时,Word要求我进行更新,并且更新正确进行。唯一的问题是更新目录始终是从左到右的方向,但我需要从右到左的方向。如何在python中使用python-docx修复该程序?