java-如何使用apache POI在docx中插入当前日期字段

我不知道如何将日期和时间字段插入docx.
我想我必须使用类似

run.getCTR().addNewFldChar().setFldCharType(STFldCharType.???) 

但我不知道如何

波纹管是一种SSCCE,其中insertCurrentXxxxField()函数的行为不符合需要.

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class InsertCurrentDateAndTimeInDocxUsingApachePOI {

    public static void main(String[] args) throws IOException {

        XWPFDocument  document  = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun       run       = paragraph.createRun();

        run.setText("Current date:");
        insertCurrentDateField(run);

        run.setText(" current time:");
        insertCurrentTimeField(run);

        FileOutputStream out = new FileOutputStream(new File("CurrentDateAndTime.docx"));
        document.write(out);
    }

    private static void insertCurrentDateField(XWPFRun run){
        run.setText("${here should be the current date field DD.MM.YY}");
    }
    private static void insertCurrentTimeField(XWPFRun run){
        run.setText("${here should be the current time field HH:MM:SS}");
    }

}

解决方法:

在Word中,字段在段落中,而不在运行中.但是必须在字段之前关闭运行,并在字段之后打开新的运行.

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class InsertCurrentDateAndTimeInDocxUsingApachePOI {

    public static void main(String[] args) throws IOException {

        XWPFDocument  document  = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun       run       = paragraph.createRun();

        run.setText("Current date:");
        insertCurrentDateField(paragraph);

        run = paragraph.createRun();
        run.setText(" current time:");
        insertCurrentTimeField(paragraph);

        FileOutputStream out = new FileOutputStream(new File("CurrentDateAndTime.docx"));
        document.write(out);
    }

    private static void insertCurrentDateField(XWPFParagraph paragraph){
        XWPFRun run = paragraph.createRun(); 
        paragraph.getCTP().addNewFldSimple().setInstr("DATE \\@ \"yyyy-MM-dd\" \\* MERGEFORMAT");
    }
    private static void insertCurrentTimeField(XWPFParagraph paragraph){
        XWPFRun run = paragraph.createRun();
        paragraph.getCTP().addNewFldSimple().setInstr("TIME \\@ \"HH:mm:ss\" \\* MERGEFORMAT");
    }

}
上一篇:校园商铺需求分析报告


下一篇:python转换doc为docx