0

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

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

我怎样才能做到这一点,当用户打开 docx 文件时,它会将方程视为 docx 方程形式。

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

提前致谢

4

1 回答 1

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

 }
}

参见CTOMathhttp://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/officeDocument/x2006/math/CTOMath.java#CTOMath 。添加NewRad%28%29

于 2016-02-17T16:31:27.257 回答