OutputStream won't save all updates on a file
-
14-11-2019 - |
Question
I'm working on a Microsoft word 2007 Document.
my Objectives are to fill :
- Table cell.
- A Paragraph line.
so,my code does this work but the problem is when i write the file using FileOutputStream, it writes only one of my objectives (the last modification only).
here is an Image of the Header :
and here is the code i used :
try{
InputStream input = new FileInputStream("c:\\doslot.docx");
XWPFDocument document=new XWPFDocument(input);
//*********************inserting the 2nd line**************************
XWPFHeader head = document.getHeaderList().get(0);
List<XWPFParagraph> para= head.getParagraphs();
XWPFRun pararun=para.get(0).createRun();
pararun.setText("DOSSIER DE LOT GLUSCAN® N°FG-4040400A");
//*********************inserting the header thrid table cell*************************
XWPFHeader headd = document.getHeaderList().get(1);
List<XWPFTable> tables = headd.getTables();
List<XWPFTableRow> rows = tables.get(0).getRows();
XWPFTableCell cell = rows.get(0).getTableCell(rows.get(0).getTableCells().get(3).getCTTc());
XWPFParagraph p =cell.addParagraph();
XWPFRun pararuno=p.createRun();
pararuno.setText("some text");
FileOutputStream out = new FileOutputStream("c:\\fin.docx");
document.write(out);
out.close();
}catch(Exception ex){
ex.printStackTrace();
}
Solution
The problem is that List<XWPFTableCell> cell = rows.get(0).getTableCells();
returns newly created list, XWPFTableRow.getTableCells() says:
create and return a list of all XWPFTableCell who belongs to this row
And ofcourse comments do lie, while code does not, so sources say:
public List<XWPFTableCell> getTableCells(){
if(tableCells == null){
//Here it is created
List<XWPFTableCell> cells = new ArrayList<XWPFTableCell>();
for (CTTc tableCell : ctRow.getTcList()) {
cells.add(new XWPFTableCell(tableCell, this, table.getPart()));
}
this.tableCells = cells;
}
return tableCells;
}
And for your help there is a XWPFTableRow.getTableCell(CTTc cell), where you pass CTTc
cell, and method definitely returns an existing object:
public XWPFTableCell getTableCell(CTTc cell) {
for(int i=0; i<tableCells.size(); i++){
if(tableCells.get(i).getCTTc() == cell) return tableCells.get(i);
}
return null;
}
You can achieve CTTc cell by invoking XWPFTableCell.getCTTc() and then modify it directly.
The code to directly access existing cell would be:
XWPFTableCell cell =
rows.getTableCell(rows.get(0).getTableCells().get(3).getCTTc());
I did not try or compile this code, so I am not sure if it is correct, but I trust my OO knowledge and sources. By all means this should do it. If it does - please correct the code to make sure it is correct and compilable.
FTR, I think that there should be more convenient way doing this, it is quite common to edit the cells and I think it should not be so complicated, I would suggest trying some tutorials on XWPFTable and its manipulation.