我有一段Java代码,使用Apache POI创建了一个Word文档并向其中添加了一些表格和文本,但它总是在最后一个文档中添加表格。我希望先写一些文本,然后添加表格,再写一些文本。
目前的问题是它会先添加表格,然后在最后一个文档中添加两个文本(Hi & Bye)。
我的代码如下:
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();
XWPFParagraph para = document.createParagraph();
XWPFRun run = para.createRun();
run.setText("Hi");
//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");
run.setText("Bye");
document.write(out);
out.close();
System.out.println("create_table.docx written successully");
}
如何在页面顶部先打印“Hi”,然后添加表格,在表格后再打印“Bye”?
每次要向文档添加内容时,如何保存文档并最终编写并打开它?
谢谢。