0

I'm working on a spring boot project using thymeleaf I need to create a Word file (.docx) based on an existing one (as a template) that contains styles, tables, images... , and also I need to modify and customize some lines at the same time. I checked some codes and answers about the Apache POI Library but nothing works for my case.

Any ideas PLEASE! Thanks and regards


I solved my problem using this code :

public void wordFileCreator() throws IOException
    {
            String filename = "Template.docx";
            try {

                XWPFDocument doc = new XWPFDocument(OPCPackage.open(new FileInputStream(filename)));
                List<XWPFParagraph> paragraphList = doc.getParagraphs();
                for (XWPFParagraph para : paragraphList) {
                    for (XWPFRun run : para.getRuns()) {
                        String text = run.text();
                        if(text.contains("StringToReplace")){
                            text = text.replace("StringToReplace", "newVal");
                            run.setText(text, 0);
                        }
                    }
                }
                doc.write(new FileOutputStream("newFile.docx"));
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
braX
  • 11,506
  • 5
  • 20
  • 33
Sarah Abouyassine
  • 169
  • 1
  • 2
  • 13
  • 1
    what did you try? share it and tell us whats wrong with it and why it didn't work – Bashir Jun 17 '20 at 09:10
  • I tried to use the code given in this answer https://stackoverflow.com/a/25375809/9770112 but, it gives an error in the copyStyle method after running the code, and it generate an empty file. – Sarah Abouyassine Jun 17 '20 at 09:25
  • 2
    Why trying copying from one `Word` file to another? Why not simply opening the template as a `XWPFDocument`, changing what is needed in that document and then writing the `XWPFDocument` into another file so the template stays unchanged? – Axel Richter Jun 17 '20 at 10:53
  • Thanks for replying .. Yeah it's a great idea and it seems to be easier, but how I can make changes on the file in specific places ? – Sarah Abouyassine Jun 17 '20 at 11:16
  • And I should conserve the style of document either – Sarah Abouyassine Jun 17 '20 at 11:42

0 Answers0