如何使用 Apache POI 将嵌入式方程添加到 docx 文件? [英] How can I add embedded equations to docx files by using Apache POI?

查看:39
本文介绍了如何使用 Apache POI 将嵌入式方程添加到 docx 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I want to add some mathematical equations in some lines.

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

How can I do this in a way that when the user open the docx file it see that equations as docx equation form.

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

I mean I don't want simply give a background colour to that run, I want when the user does double click on my equation MS-Word open it in equation forms.

提前致谢

推荐答案

这并不复杂:

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.

这篇关于如何使用 Apache POI 将嵌入式方程添加到 docx 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆