如何使用Apache POI将嵌入式方程式添加到docx文件中?

时间:2016-02-15 20:27:44

标签: apache-poi xwpf

我想通过Apache POI以编程方式创建一个docx文件。

我想在某些行中添加一些数学方程式。

我怎么能这样做,当用户打开docx文件时,它会看到方程式为docx方程式。

我的意思是我不想简单地为该游戏提供背景颜色,我希望当用户双击我的等式时MS-Word以等式形式打开它。

提前致谢

1 个答案:

答案 0 :(得分:2)

这并不复杂:

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"));

 }
}

对于CTOMath,请参阅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