简体   繁体   English

如何使用 python-docx 将分数输入到 WORD 文档中

[英]How to input fractions into WORD document using python-docx

I want to insert fractions into WORD using python-docx, like below result in picture.我想使用 python-docx 将分数插入 WORD,如下图所示。 I can only insert these: 15/20 + 4/20.我只能插入这些:15/20 + 4/20。 I want to have the style look like the picture shows.我想让风格看起来像图片所示。 Is it possible to do it using python-docx, or other library in Python?是否可以使用 python-docx 或 Python 中的其他库来做到这一点?

分数

Python-docx doesn't implement a high-level API for working with Word formulas, but if you can construct the MathML XML string yourself, you can insert it into a document. Python-docx 没有实现用于处理 Word 公式的高级 API,但如果您可以自己构造 MathML XML 字符串,则可以将其插入文档中。

from docx import Document
from docx.oxml import parse_xml

document = Document()

p = document.add_paragraph()
mathml_xml = '<p xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:oMathPara><m:oMath><m:f><m:num><m:r><m:t>1</m:t></m:r></m:num><m:den><m:r><m:t>2</m:t></m:r></m:den></m:f></m:oMath></m:oMathPara></p>'
mathml_el = parse_xml(mathml_xml)[0]
p._p.append(mathml_el)

document.save('demo.docx')

Here's that MathML fragment:这是 MathML 片段:

<p xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">
  <m:oMathPara>
    <m:oMath>
      <m:f>
        <m:num>
          <m:r>
            <m:t>1</m:t>
          </m:r>
        </m:num>
        <m:den>
          <m:r>
            <m:t>2</m:t>
          </m:r>
        </m:den>
      </m:f>
    </m:oMath>
  </m:oMathPara>
</p>

That produces a Word doc with the fraction 1/2.这会产生一个分数为 1/2 的 Word 文档。

显示分数 1/2 的屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM