1 回答

TA貢獻1853條經驗 獲得超9個贊
在這種情況下,我正在做的事情如下:首先,Word使用Word GUI. 然后查看Word已創建的內容,了解需要使用apache poi.
具體來說:創建最簡單的表,其中Word有一個字段{=SUM(ABOVE)}。將其另存為*.docx. 現在解壓縮*.docx(Office Open XML 文件*.docx只是ZIP存檔)??纯?word/document.xml那個檔案。在那里你會發現類似的東西:
<w:tc>
<w:p>
<w:fldSimple w:instr="=SUM(ABOVE)"/>
...
</w:p>
</w:tc>
這XML適用于具有段落的表格單元格,fldSimple段落中有一個元素,其中instr屬性包含公式。
現在我們知道,我們需要表格單元格XWPFTableCell和XWPFParagraph其中的 。然后我們需要 fldSimple在此段落中設置一個元素,其中instr屬性包含公式。
這很簡單
paragraphInCell.getCTP().addNewFldSimple().setInstr("=SUM(ABOVE)");
但是當然有些東西必須告訴Word在文檔打開時需要計算公式。最簡單的解決方案是將字段設置為“臟”。這導致需要在打開文檔時更新字段Word。它還會導致有關更新需求的確認消息對話框。
完整示例使用apache poi 4.1.0:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;
public class CreateWordTableSumAbove {
public static void main(String[] args) throws Exception {
XWPFDocument document= new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The table:");
//create the table
XWPFTable table = document.createTable(4,3);
table.setWidth("100%");
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (col < 2) table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
else table.getRow(row).getCell(col).setText("" + ((row + 1) * 1234));
}
}
//set Sum row
table.getRow(3).getCell(0).setText("Sum:");
//get paragraph from cell where the sum field shall be contained
XWPFParagraph paragraphInCell = null;
if (table.getRow(3).getCell(2).getParagraphs().size() == 0) paragraphInCell = table.getRow(3).getCell(2).addParagraph();
else paragraphInCell = table.getRow(3).getCell(2).getParagraphs().get(0);
//set sum field in
CTSimpleField sumAbove = paragraphInCell.getCTP().addNewFldSimple();
sumAbove.setInstr("=SUM(ABOVE)");
//set sum field dirty, so it must be calculated while opening the document
sumAbove.setDirty(STOnOff.TRUE);
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("create_table.docx");
document.write(out);
out.close();
document.close();
}
}
這一切只有在使用打開文檔時才能正常工作Microsoft Word。LibreOffice Writer無法將此類公式字段存儲為Office Open XML( *.docx) 格式,也無法Office Open XML正確讀取此類公式字段。
添加回答
舉報