我一直在使用python-docx来生成大文件,其中包含符合标准模板的表格和图形。我发现了如何使用https://github.com/python-openxml/python-docx/issues/359将它们交叉引用。但是,这会在每节中从1开始标记我的图形/表格,一直到下一节从1重新开始。
我希望图形编号取决于部分编号(即第二部分中的第一个图形=图2.1等)。有人知道这是否可能吗?
当前编号是由函数产生的:
def Table(paragraph):
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
run = run = paragraph.add_run()
r = run._r
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' SEQ TableMain \* ARABIC \s 1 '
print instrText
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
由以下代码调用,该代码也填充表格以及表格标题和页脚
table3 = document.add_table(rows=1, cols=1)
table3.cell(0,0).text="Table "
for paragraph in table4.cell(0,0).paragraphs:
paragraph.style = document.styles['Caption']
Table(paragraph)
paragraph.add_run(text="this is the full table name")
row_cells = table3.add_row().cells
call_func_that_makes_actual_table(row_cells[0],...)
row_cells = table3.add_row().cells
row_cells[0].text="Source: ..."
for paragraph in row_cells[0].paragraphs:
paragraph.style = document.styles['Source']
这会产生一个像 this
我希望表编号像 this
答案 0 :(得分:0)
设法自己解决这个问题,解决方案正在添加其他功能:
def section(paragraph):
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
run = run = paragraph.add_run()
r = run._r
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.text = ' STYLEREF 1 \s '
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
并将呼叫更改为:
for paragraph in table.cell(1,0).paragraphs:
paragraph.style = document.styles['Caption']
section(paragraph)
paragraph.add_run(text=".")
Figure(paragraph)
paragraph.add_run(text=": this is the full table name")