Search code examples
pythonpython-docx

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. I can only insert these: 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?

fractions


Solution

  • Python-docx doesn't implement a high-level API for working with Word formulas, but if you can construct the XML string yourself, you can insert it into a document. The XML Schema is Microsoft OMML, which is conceptually similar to MathML.

    from docx import Document
    from docx.oxml import parse_xml
    
    document = Document()
    
    p = document.add_paragraph()
    omml_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>'
    omml_el = parse_xml(omml_xml)[0]
    p._p.append(omml_el)
    
    document.save('demo.docx')
    

    Here's that OMML fragment:

    <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.

    Screenshot showing the fraction 1/2