SoFunction
Updated on 2025-04-14

Implement template filling Word based on Java

Java implementation fills word by template

The requirements explained in this article are: we need to fill some data in the database according to the word template provided by the product manager, fill some content in the data table into the word template according to the template, and then export the word template in the form of pdf. We can conduct a research according to our needs, or we can only export it in the form of word.

The following code:

Template file, we put the template file into the static directory under the resources package (resource root)

First, the path to output the temporary word is defined (because our goal is to finally obtain the pdf file, if you want to obtain the word, it can be directly your target storage location)

Defines the path to the final download of our pdf

(In the project, the download path is usually sent to us by the front-end. We don’t need to set it ourselves, we can get it through response)

 	    // Clear template cache        ();
        //Passed to the front end        ("UTF-8"); // Set the encoding format        //Set the Header field        // file name        String fileName = "Template.docx";
        String encodedFileName = (fileName, "UTF-8");
        // Encode the file name        ("Content-disposition", "attachment;filename=" + encodedFileName);
        // Obtain the output stream        OutputStream out = ();
        (out);

The following is to define the data we want to fill. Note that when we do word template filling, we use poi dependencies, so the value must be of String type

These data are some fake data I set myself. In real needs, we need to obtain it from the database.

Then the two methods were called to perform different operations separately

// This is the method of filling word in templatesfillWordTemplate(templatePath, outputWordPath, map);
/** The first parameter is the template file
	 The second parameter is the path to the output word, which is where to download it after the template is filled in.
	 The third parameter is the corresponding data relationship
 */
 ((outputWordPath));
//When the target is a pdf file, help us delete the word file
 @Test
    public void testWORDPDF() throws IOException {
        //Get the template file under the static package        String templatePath = "/static/test document.docx";
        // Output temporary Word file path (for subsequent conversion to PDF)        String outputWordPath = "D:\\Users\\lenovo\\Desktop\\Template.docx";
        //Give the path to download the pdf. Get it through () in the project        String PDFpath = "D:\\Users\\lenovo\\Desktop\\test.pdf";

        //Simulate the data to be filled. The project is obtained from the database, but it must be ensured that the data to be filled must be of String type        Map<String, String> map = new HashMap<>();
        ("username", "Nohara Shinnosuke");
        ("year", "5 years old");
        ("text", "Advantages: lively, active, optimistic, cute, innovative, good motor nerves (every time I run with Kawamura Leopard, and I can do many difficult movements), considerate but not frank.\n" +
                "Disadvantages: picky eaters, lustful, naughty, precocious, forgetful, dull (sometimes depending on the situation), and love to be mean.\n" +
                "Favorites:\n" +
                "The characters I like include Dynamic Superman, Steel Bullet Warrior, Fatty Dudu Saemon (Shi Shin's own character), and Pencil Shin (after the broadcast, I was very popular with Shin and his friends, but my parents protested).\n" +
                "The sports I like include Kendo (the purpose of learning Kendo is to win the strong enemy Yoyogi), football, dodgeball, and baseball. (Sometimes treating bare butt dance as a sport), boxing (in this chapter of "This is Youth", Shin-shi, who became a hobby when he was a junior high school student), and swimming.\n" +
                "I like to play the role of the bare butt Superman dance (also known as the butt-exposed alien), the elephant dance, putting my mother's underwear on her head, learning to laugh dynamically, emitting dynamic light waves, and shy laughing with her head touching. [1]\n" +
                "Favorite foods include chocolate biscuits (available in Japanese stores and endorsed by Xiaoxin), bibimbap, curry, hot pot, fries, shaved ice, ice cream, pudding, cakes, potato chips (potato chips), senbei (snacks), sushi, etc.\n" +
                "I like drinks include 100% pure juice, cola, green tea (a little thicker) pus light (there is this logo on the bottle).\n" +
                "The singer I like is the uncle who sang the theme song of "Dynamic Superman".\n" +
                "The animals I like include Xiaobai (the stray dog ​​I picked up, full name is Nohara Xiaobai), Chicken (named by Shin-shi: Sparrow), Cat (named by Shin-shi: Question mark), Elephant, Hamster (Masaman's hamster gave birth to a baby, please ask Shin-shi to raise one, Shin-shi, Malaya, and another cat (named by Shin-shi: Marilyn, is a cat from Shin-shi Matsusaka).\n" +
                "I like movies like "Motion Superman" and "Gangdam Warriors".\n" +
                "The people I like include Ohara Nanako, Kim Yoominko, and Xiao Tsuka.\n" +
                "If you like girls, you should have big breasts, over 15 years old, have a cute and beautiful face and a good figure. [1]\n" +
                "Disgust:\n" +
                "The foods that are pestos, carrots, natto without scallions and miso soup with broccoli, and onions.");

        //Fill the template
        // Convert the filled Word document to PDF        try {
            (templatePath, outputWordPath, map);
            (outputWordPath, PDFpath);
            // //The following can add code to implement download logic, such as returning to the client through a response stream            ("The PDF file has been generated, the path is:" + PDFpath);
        } catch (Exception e) {
            ();
        }
            ((outputWordPath));  //Delete temporary files    }

The following method is the method to download the word template after filling it

First, we have developed a template and set the tag ${}; note that this corresponds to your word template. You need to take care of where you want to fill in the data.

//For example worduser:${username}

Because our template file is under the resources package (which meets the real project scenario here), we need to get it first

InputStream is = (templatePath);
//After using the ResourceLoader class and obtaining the stream through reflection, we obtain the file input stream through our template file at the source root path of the resources package

template object we created

Then we use the method of (template file input stream, template mark fills data) to fill templates

Here I used a buffer file tempFile to help me overdo it, because I have to do some style operations later (play some fun)

So I write the file filled with the template to tempFile // ((tempFile));// Write the file

The following operations are some tricks, you can't watch them, usually not use them

The first thing you get here is the input stream of buffered files

Then create a word document object that buffers the file

Then iterates through the paragraphs in it, and gets the text content after traversing

If the content is not empty, do some style modification

Color Blue Font Size 12 Font Kaiyi Spacing 10

And set the paragraph to be aligned to the left

Finally, delete the buffered file

Download the word document object into the defined path

 public void fillWordTemplate(String templatePath, String outputWordPath, Map dataMap) throws Exception {
        ConfigureBuilder builder = ();
        ("${", "}");  // Settings Template Tags        XWPFTemplate template;  // Create template object        //Get the template file        InputStream is = (templatePath);
        ("is = " + is);
        // Custom paragraph style (set the font to Song font, font size is 12, color is red)        template = (is, ()).render(dataMap);
        File tempFile = ("temp", ".docx");
        ((tempFile));// Write to the file

        FileInputStream fis = new FileInputStream(tempFile);
        XWPFDocument xwpfDocument = new XWPFDocument(fis);
        for (XWPFParagraph paragraph : ()) {
            for (XWPFRun run : ()) {
                if ((0) != null) {
                    ("0000FF");
                    (12);
                    ("Kai Style");
                    (10);// Set text spacing                    //Set the content to center horizontally                }
            }
            //Set the content to be aligned to the left            ();
        }

        ();
        (((outputWordPath)));
        ();
        ();
        ();
    }

The following method is the method of converting word into pdf

Convert Word files to PDF files using the aspose-words library (operated through LocalConverter-related classes)

First, the two parameters passed in the first is the download path of the file filled with the word template. The second parameter is the target path to download by pdf

Then we get the file input stream and the output stream of the pdf file

Then we construct a converter object in the aspose-words library through the constructor mode

// Actual execution(doc).as().to(outputStream).as().execute();
//Convert doc file type doc to pdf to output stream//The return result of the method is whether the conversion is successful

Success We turn off the converter

Close the doc input stream, pdf output stream

public void wordToPdf(String inputWordPath, String outputPdfPath) {
        try {
            InputStream doc = ((inputWordPath));
            OutputStream outputStream = ((outputPdfPath));
            IConverter converter = ().build();
            boolean flag = (doc).as().to(outputStream).as().execute();
            if (flag) {
                ();
            }
            ();
            ();
            ("The PDF file has been generated, the path is:" + outputPdfPath);
        } catch (Exception e) {
            ();
        }
    }

Maven dependencies required

    <dependency>
            <groupId></groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        

        <dependency>
            <groupId></groupId>
            <artifactId>poi</artifactId>
            <version>5.2.3</version>
            <exclusions>
                <exclusion>
                    <groupId>.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.12.2</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>poi</artifactId>
                    <groupId></groupId>
                </exclusion>
                <exclusion>
                    <groupId>.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId></groupId>
                    <artifactId>poi-ooxml</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.17.2</version>
        </dependency>
        <dependency>
            <groupId>.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.2</version>
            <exclusions>
                <exclusion>
                    <groupId>.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-local</artifactId>
            <version>1.1.6</version>
        </dependency>

        <dependency>
            <groupId>com.documents4j</groupId>
            <artifactId>documents4j-transformer-msoffice-word</artifactId>
            <version>1.1.6</version>
        </dependency>

This is the end of this article about filling Word based on Java templates. For more related Java templates and filling Word content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!