サンプル
* テンプレートを読み込んで「@@VER@@」を「Hello World!!」に置き換えるサンプル
=> ただし不十分で、表の中の文字置き換えには対応できていない(他にもありそうだが)ので注意
ReplaceWithPoiDemo.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class ReplaceWithPoiDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
String inputFilePath = System.getProperty("user.dir") + "/template.docx";
String outputFilePath = System.getProperty("user.dir") + "/output.docx";
try (XWPFDocument document = new XWPFDocument(new FileInputStream(inputFilePath));) {
for (XWPFParagraph paragraph : document.getParagraphs()) {
int numberOfRuns = paragraph.getRuns().size();
// Collate text of all runs
StringBuilder stringBuilder = new StringBuilder();
for (XWPFRun run : paragraph.getRuns()) {
int position = run.getTextPosition();
if (run.getText(position) != null) {
stringBuilder.append(run.getText(position));
}
}
// Continue if there is text and contains "@@VER@@"
if (stringBuilder.length() > 0 && stringBuilder.toString().contains("@@VER@@")) {
// Remove all existing runs
for (int i = 0; i < numberOfRuns; i++) {
paragraph.removeRun(i);
}
String text = stringBuilder.toString().replace("@@VER@@", "Hello World!!");
// Add new run with updated text
XWPFRun run = paragraph.createRun();
run.setText(text);
paragraph.addRun(run);
}
}
document.write(new FileOutputStream(outputFilePath));
}
System.out.println("Done. See " + outputFilePath);
}
}