I tried to change a value of a xlsx-file which is embedded in a docx-file with apache poi. Sadly, I havent found a proper solution to this problem. After running my programm, the new created docx-file with the embedded xlsx-table hasnt changed. Here is what I have tried so far:
FileInputStream fis = new FileInputStream("old.docx");
XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
System.out.println(xdoc.getAllEmbedds().get(0));
File file2 = new File("new.docx");
for (PackagePart pPart : xdoc.getAllEmbedds()) {
String contentType = pPart.getContentType();
// Excel Workbook - OpenXML file format
if (contentType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
XSSFWorkbook embeddedWorkbook = new XSSFWorkbook(pPart.getInputStream());
XSSFSheet sheet = embeddedWorkbook.getSheetAt(0);
sheet.getRow(1).getCell(1).setCellValue("someValue"); //change value here
embeddedWorkbook.write(pPart.getOutputStream());
}
}
xdoc.write(new FileOutputStream(file2));
any idea how to fix this problem?
I don't believe that this will be possible with fulfillment of all wishes. In fact, the embedded
XSSFWorkbook
is updated. But what you see if you open thenew.docx
is not theXSSFWorkbook
but aEMF
picture of it. This picture will only be updated if you doubleclick it to opening the embeddedXSSFWorkbook
and then click outside it to close it again.Some other posts suggest that it will be updated while opening the
Word
file if thisEMF
picture is not actually within theZIP
archive. But it will not.Try:
So the "solution" would be, new creating a
EMF
snapshot picture form the updatedXSSFWorkbook
and replace the oldEMF
picture with this new one. Not really possible in my opinion.Seems as if the program routine for creating the
EMF
snapshot picture is part of theWord
application if the embeddedXSSFWorkbook
is closed. But it is not part ofapache-poi
until now. And of course it is not part of theXML
program routines.