サンプル
* テンプレートを読み込んで表内の「@@VER2@@」を「Hello World!!」に置き換えるサンプル
ReplaceInTableWithPoiDemo.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class PoiDemo {
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 (InputStream fis = new FileInputStream(inputFilePath); XWPFDocument document = new XWPFDocument(fis);) {
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (int x = 0; x < paragraphs.size(); x++) {
XWPFParagraph paragraph = paragraphs.get(x);
System.out.println(paragraph.getParagraphText());
}
List<XWPFTable> tables = document.getTables();
for (int x = 0; x < tables.size(); x++) {
XWPFTable table = tables.get(x);
List<XWPFTableRow> tableRows = table.getRows();
tableRows.remove(x);
for (int r = 0; r < tableRows.size(); r++) {
System.out.println("Row " + (r + 1) + ":");
XWPFTableRow tableRow = tableRows.get(r);
List<XWPFTableCell> tableCells = tableRow.getTableCells();
for (int c = 0; c < tableCells.size(); c++) {
System.out.print("Column " + (c + 1) + ": ");
XWPFTableCell tableCell = tableCells.get(c);
// tableCell.setText("TAE");
String tableCellVal = tableCell.getText();
if ((c + 1) == 2) {
if (tableCellVal != null) {
if (tableCellVal.length() > 0) {
String replaecedText = null;
if (tableCellVal.contains("@@VER2@@")) {
replaecedText = tableCellVal.replace("@@VER2@@", "Hello World!");
}
if (replaecedText != null) {
removeParagraphs(tableCell);
tableCell.setText(replaecedText);
}
} else {
// tableCell.setText("NULL");
}
}
}
System.out.println("tableCell.getText(" + (c) + "):" + tableCellVal);
}
}
System.out.println("\n");
}
document.write(new FileOutputStream(outputFilePath));
}
System.out.println("Done. See " + outputFilePath);
}
private static void removeParagraphs(XWPFTableCell tableCell) {
for (int i = 0; i < tableCell.getParagraphs().size(); i++) {
tableCell.removeParagraph(i);
}
}
}