gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:39:55 27 4
gpt4 key购买 nike

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

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

但我不知道怎么办。

Bellow 是一个 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 中,字段在 Paragraph 中,而不是在 Run 中。但是 Run 必须在该字段之前关闭,并且必须在该字段之后打开一个新的 Run

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

}

关于java - 如何使用 apache POI 在 docx 中插入当前日期字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35056982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com