How can I add embedded equations to docx files by using Apache POI?

前端 未结 1 964
天命终不由人
天命终不由人 2021-01-07 16:05

I want to create a docx file programatically via Apache POI.

I want to add some mathematical equations in some lines.

How can I do this in a way that when th

相关标签:
1条回答
  • 2021-01-07 16:25

    This is not really complicated:

    import java.io.FileOutputStream;
    
    import org.apache.poi.xwpf.usermodel.*;
    
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTRad;
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;
    import org.openxmlformats.schemas.officeDocument.x2006.math.STStyle;
    /*
    To
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTRad;
    import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;
    import org.openxmlformats.schemas.officeDocument.x2006.math.STStyle;
    the fully ooxml-schemas-1.3.jar is needed as mentioned in https://poi.apache.org/faq.html#faq-N10025
    */
    
    public class CreateWordFormula {
    
     public static void main(String[] args) throws Exception {
    
      XWPFDocument doc= new XWPFDocument();
    
      XWPFParagraph paragraph = doc.createParagraph();
      XWPFRun run=paragraph.createRun();  
      run.setText("The Formula: ");
    
      CTOMath cTOMath = paragraph.getCTP().addNewOMath();
      CTR cTR = cTOMath.addNewR();
      cTR.addNewRPr().addNewSty().setVal(STStyle.P);
      cTR.addNewT2().setStringValue("a²+b²=c²");
    
      run=paragraph.createRun();  
      run.setText(" text after the formula");
    
      paragraph = doc.createParagraph();
      run=paragraph.createRun();  
      run.setText("The Formula: ");
    
      cTOMath = paragraph.getCTP().addNewOMath();
      CTRad cTRad = cTOMath.addNewRad();
      cTR = cTRad.addNewDeg().addNewR();
      cTR.addNewRPr().addNewSty().setVal(STStyle.P);
      cTR.addNewT2().setStringValue("2");
      cTR = cTRad.addNewE().addNewR();
      cTR.addNewRPr().addNewSty().setVal(STStyle.P);
      cTR.addNewT2().setStringValue("a²+b²");
    
      run=paragraph.createRun();  
      run.setText(" text after the formula");  
    
      doc.write(new FileOutputStream("WordFormula.docx"));
    
     }
    }
    

    For CTOMath see http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/officeDocument/x2006/math/CTOMath.java#CTOMath.addNewRad%28%29.

    0 讨论(0)
提交回复
热议问题