wordで作成中のレポートに追加で大量の図を貼り付ける必要が出たため、python-docxで図とその図番号を貼り付けようとしています。
以下のページを参考に図の貼り付けと図番号の作成を行いました。
結果として図の貼り付けは上手くいったのですが、field更新をしても図番号の表示がFigure0-80のように謎の0と80が全角になってしまいます。
(例:wordで作成した最後の図番号がFigure 79の場合、python docxで作成した図番号はページの最後にあるとFIgre0-80になる)
どなたかこの図番号の0の消去と80の部分を半角に直す方法を教えていただけないでしょうか。
OSのversionはWindows10
wordは2016
pythonは3.9.12
python-docxのversionは0.8.11
参考のためにコードの該当部分を以下に載せておきます。
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Inches
from attrdict import AttrDict
from pathlib import Path
word_path = Path(r'C:\Users\Documents')
fig_path = word_path/'figure'
def Figure(elm,paragraph):
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 = u' STYLEREF 2 \s'
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
run = paragraph.add_run(u'-')
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 = u' SEQ Figure \* DBCHAR'
r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
r.append(fldChar)
run = paragraph.add_run(u' '+elm)
document = Document(word_path/'test.docx')
p = document.add_paragraph(u'文の挿入 ')
p.add_run(u'太字').bold = True
p.add_run(' and some ')
p.add_run(u'斜線.').italic = True
document.add_heading(u'見出し1', level=1)
document.add_paragraph(u'本文1で長い文章をかいてもらいたいということなんで書いた。改行も試験したいのでこんなに長い文になってしまった。')
document.add_heading(u'見出し2', level=2)
document.add_paragraph(u'本文2')
document.add_heading(u'見出し3', level=3)
document.add_paragraph(u'本文3')
document.add_picture(str(fig_path/'test.png'), width=Inches(1.25))
pg = document.add_paragraph(u'Figure',style='Caption')
Figure(u'図の名称',pg)
document.add_page_break()
document.save(word_path/'demo.docx')