我有一张桌子的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();
}
}
最佳答案
public class TableCreate{
public static void main(String[] args)throws Exception {
//Blank Document
XWPFDocument document= new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream(
new File("create_table.docx"));
//create table
XWPFTable table = document.createTable();
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("col one, row one");
tableRowOne.addNewTableCell().setText("col two, row one");
tableRowOne.addNewTableCell().setText("col three, row one");
//create second row
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("col one, row two");
tableRowTwo.getCell(1).setText("col two, row two");
tableRowTwo.getCell(2).setText("col three, row two");
//create third row
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("col one, row three");
tableRowThree.getCell(1).setText("col two, row three");
tableRowThree.getCell(2).setText("col three, row three");
document.write(out);
out.close();
System.out.println("create_table.docx written successully");
}
}
输出量