【发布时间】:2016-10-25 06:12:21
【问题描述】:
我有一个带表格的 word 文档。我想使用 Java 在这些单元格中插入文本,并且我已将 Apache POI 添加到我的项目中。
但是,我只成功地读取了文档。我的应用程序获取表格中的所有单元格。但我不知道如何在每个单元格中插入新文本?有什么想法吗?
String SOURCE_FILE = "template.doc";
DocumentProcessor instance = new DocumentProcessor();
HWPFDocument doc = null;
try {
doc = instance.openDocument(SOURCE_FILE);
Range range = doc.getRange();
TableIterator itr = new TableIterator(range);
while(itr.hasNext()) {
Table table = itr.next();
for (int rowIndex = 0; rowIndex < table.numRows(); rowIndex++) {
TableRow row = table.getRow(rowIndex);
for (int colIndex = 0; colIndex < row.numCells(); colIndex++) {
TableCell cell = row.getCell(colIndex);
cell.getParagraph(0).text().replace("", "Hello");
System.out.println(cell.getParagraph(0).text());
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
saveDocument(doc, SOURCE_FILE);
}
}
private HWPFDocument openDocument(String file) throws Exception {
URL res = getClass().getClassLoader().getResource(file);
HWPFDocument document = null;
if (res != null) {
document = new HWPFDocument(new POIFSFileSystem(
new File(res.getPath())));
}
return document;
}
private static void saveDocument(HWPFDocument doc, String file) {
try (FileOutputStream out = new FileOutputStream(file)) {
doc.write(out);
doc.close();
System.out.println("File saved");
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
标签: java apache apache-poi