There is already an existing word document with the header and footer and some text in the front page. The body of the word document is empty. I need to create a table everytime (or overwrite the previous)which is in the second page of the word document. I am creating a table from scratch and trying the update the word document. However I am getting an error. Below is my code
XWPFDocument document = new XWPFDocument(OPCPackage.open(source
"Testword.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(new FileOutputStream(source
"Testword.docx")); // This line is generating an error
The error is
Exception in thread "main" org.apache.poi.ooxml.POIXMLException: java.io.EOFException: Unexpected end of ZLIB input stream
CodePudding user response:
public static void main(String[] args) throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("D:\\Testword.docx");
XWPFDocument document = new XWPFDocument(is);
is.close();
//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");
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Testword.docx");
document.write(fileOutputStream);
fileOutputStream.close();
}