Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Programmatic Word Document Generation with Apache POI

Tech 1

Add the following dependencies to your Maven configuration:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
</dependencies>

The following implementation demonstrates creating a structured Word template:

import org.apache.poi.xwpf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;

public class DocumentGenerator {
    
    public void exportToFile(String outputPath) {
        XWPFDocument doc = new XWPFDocument();
        
        XWPFParagraph titlePara = doc.createParagraph();
        titlePara.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titlePara.createRun();
        titleRun.setText("Report Template");
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        
        XWPFParagraph contentPara = doc.createParagraph();
        XWPFRun contentRun = contentPara.createRun();
        contentRun.setText("Dynamic content section");
        
        try (FileOutputStream out = new FileOutputStream(outputPath)) {
            doc.write(out);
        } catch (IOException e) {
            throw new RuntimeException("Document generation error", e);
        } finally {
            try {
                doc.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        new DocumentGenerator().exportToFile("output.docx");
    }
}

To variable substitution within exitsing templates, read the source file before processing:

import java.io.FileInputStream;

public void populateTemplate(String templatePath, String targetPath, String replacement) {
    try (XWPFDocument template = new XWPFDocument(new FileInputStream(templatePath));
         FileOutputStream out = new FileOutputStream(targetPath)) {
        
        for (XWPFParagraph paragraph : template.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null && text.contains("{{placeholder}}")) {
                    run.setText(text.replace("{{placeholder}}", replacement), 0);
                }
            }
        }
        
        template.write(out);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.