Replace Placeholder in word document with dynamic text in JAVA

109 Views Asked by At

I am trying to replace macros (placeholders) in the Word document with actual values in Java using the Apache POI library.

I am able to do this for all the pages except the first title page and table of contents.
Is there a way to replace placeholders on the title page and table of contents?

enter image description here

Below is the code I am trying to replace placeholders.

import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class WordMacroReplacement {

    public static void main(String[] args) {
        try {
            // Load the existing Word document
            
            FileInputStream fis = new FileInputStream("C:\\Users\\prsh01\\Downloads\\Test.docx");
            XWPFDocument document = new XWPFDocument(fis);

            // Define your macro replacements
            Map<String, String> macroReplacements = new HashMap<>();
            macroReplacements.put("«SOURCE_VERSION»", "2018");
            macroReplacements.put("«TARGET_VERSION»", "2023");
            macroReplacements.put("«CLIENT_NAME»", "MyClient");
            // Add more macros as needed

            // Replace macros in the document
            replaceMacrosInDocument(document, macroReplacements);

            // Save the updated document
            File targetFile = new File("Updated.docx");
            FileOutputStream fos = new FileOutputStream(targetFile);
            document.write(fos);

            // Close the streams
            fis.close();
            fos.close();
            Desktop.getDesktop().open(targetFile);
            System.out.println("Word document updated successfully.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void replaceMacrosInDocument(XWPFDocument document,
                                                Map<String, String> replacements) {
        // Replace macros in paragraphs

        for (XWPFParagraph paragraph : document.getParagraphs()) {
            replaceMacrosInParagraph(paragraph, replacements);
        }

        // Replace macros in tables
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        replaceMacrosInParagraph(paragraph, replacements);
                    }
                }
            }
        }

        // Replace macros in headers
        for (XWPFHeader header : document.getHeaderList()) {
            for (XWPFParagraph paragraph : header.getParagraphs()) {
                replaceMacrosInParagraph(paragraph, replacements);
            }
        }

        // Replace macros in footers
        for (XWPFFooter footer : document.getFooterList()) {
            for (XWPFParagraph paragraph : footer.getParagraphs()) {
                replaceMacrosInParagraph(paragraph, replacements);
            }
        }
    }

    private static void replaceMacrosInParagraph(XWPFParagraph paragraph,
                                                 Map<String, String> replacements) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);

            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    text = text.replace(entry.getKey(), entry.getValue());
                }
                run.setText(text, 0);
            }
        }
    }
}

Word document

Word File

0

There are 0 best solutions below