2016-02-15 48 views
0

我想通過Apache POI以編程方式創建一個docx文件。如何使用Apache POI將嵌入式等式添加到docx文件?

我想在一些行中添加一些數學方程。

我該如何做到這一點,當用戶打開docx文件,它可以看到方程爲docx方程形式。

我的意思是我不想簡單地給背景顏色運行,我希望當用戶雙擊我的方程MS-Word以等式形式打開它。提前

+0

這也可以是另一種選擇:http://stackoverflow.com/questions/16784914/how-generate-docx-odt-file-with-math-formulas-from-java –

回答

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.addNewRad%28%29

相關問題