introduce

Hello, everyone. I am a knowledge seeker. Today, I will introduce a Word template generator. Work often encountered this situation, the background data to fill the Word template, and then generate a rendering template to generate a new Word for download; For instance student transcript, unit contract, submit an expense account charge to wait! If you can control a suitable Java generated Word template tool, will greatly improve our development efficiency!Copy the code

Official document: deepoove.com/poi-tl

Why poI-TL

Content support

Function of the engine describe
The text Render the label as text
The picture Render the label as a picture
form Render the label as a table
The list of Render labels as lists
The chart Bar chart (3D bar chart), bar chart (3D bar chart), area chart (3D area chart), broken line chart (3D broken line chart), radar chart, pie chart (3D pie chart) and other chart rendering
The If Condition judgment Hide or display document content (including text, paragraphs, images, tables, lists, charts, etc.)
The Foreach Loop cycle Loop through some document content (text, paragraphs, images, tables, lists, charts, etc.)
Loop table row Loop over a row of the table
Loop your table column Loop over a column of the table
Loop ordered list Support the loop of ordered lists, and support multi-level lists
replace Replace the original image with another image
Bookmarks, anchors, hyperlinks Supports bookmarks, document anchors and hyperlinks
Powerful expressions Full support for SpringEL expressions, extending more expressions: OGNL, MVEL…
Label the custom Supports user-defined label prefixes and suffixes
The text box Text box inside the label support
style Templates are styles, and code can also set styles
Nested template Templates contain child templates, and child templates contain child templates
merge Word Merge, or Merge at a specified location
User-defined functions (plug-ins) Execute functions anywhere in the document

The core code

Core code, fill the data into the template to generate a new Word;

 private static Logger logger = LoggerFactory.getLogger(TemplateController.class);


   / * * *@author lsc
    * @paramTemplatePath Word Template file path *@paramFileDir Specifies the location where the generated files are stored@paramFileName indicates the generated fileName *@paramParamMap Parameter set *@returnReturn the path generated by word */
    public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) {
        Assert.notNull(templatePath, "Word template file path cannot be empty");
        Assert.notNull(fileDir, "Generated file storage address cannot be empty");
        Assert.notNull(fileName, "Generated file name cannot be empty");
        File dir = new File(fileDir);
        if(! dir.exists()) { logger.info("Directory does not exist, create folder {}!", fileDir);
            dir.mkdirs();
        }
        String filePath = fileDir +"\ \"+ fileName;
        // Read the template render parameters
        XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
        try {
            // Write the template parameters to the path
            template.writeToFile(filePath);
            template.close();
        } catch (Exception e) {
            logger.error("Generate word exception {}", e.getMessage());
            e.printStackTrace();
        }
        return filePath;
    }
Copy the code

Render string

{{value}} template

Rendering code

public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        // Render text

        params.put("dep"."Knowledge R&d Centre");
        params.put("apply_man"."Knowledge seekers");
        params.put("project"."Cost of setting up personal website https://zszxz.com/index");
        params.put("money"."19998");
        params.put("count"."8");
        params.put("year"."2020");
        params.put("month".".");
        params.put("day"."8");
		
    	// Template path
        String templatePath = "C:/mydata/generator/demo/template.docx";
        // Generate word path
        String fileDir = "C:/mydata/generator/demo";
        // Generate a word file
        String fileName = "zszxz.docx";

        String wordPath = createWord(templatePath, fileDir, fileName, params);
        System.out.println("Generate document path:" + wordPath);
    }
Copy the code

To generate the sample

Apply colours to a drawing form

Table template {{#table0}}

Rendering code

public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();

        params.pables.of(new String[][] {
                        new String[] { "19998"."8" ,"apply_man"."Cost of setting up personal website https://zszxz.com/index"},
                        new String[] { "19998"."8" ,"apply_man"."Cost of setting up personal website https://zszxz.com/index"},
                }).border(TableStyle.BorderStyle.DEFAULT).create
        String templatePath = "C:/mydata/generator/demo/template.docx";
        // Generate word path
        String fileDir = "C:/mydata/generator/demo";
        // Generate a word file
        String fileName = "zszxz.docx";

        String wordPath = createWord(templatePath, fileDir, fileName, params);
        System.out.println("Generate document path:" + wordPath);
    }
Copy the code

The renderings

Render loop

There are some problems in such rendered forms that cannot be rendered according to the template cycle defined by us. For example, multiple records in expense reimbursement details need to be used in the form cycle.

The template

Entity class

/ * * *@author lsc
 * <p> </p>
 */
public class Money {

    private String apply_man;

    private String project;

    private String money;

    private String count;
    // omit set get
}    
Copy the code

The core code

public static void main(String[] args) throws IOException {
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        Money money1 = new Money();
        money1.setApply_man("Knowledge seekers");
        money1.setProject("Cost of setting up personal website https://zszxz.com/index");
        money1.setCount("8");
        money1.setMoney("19988");
        Money money2 = new Money();
        money2.setApply_man("Knowledge seekers");
        money2.setProject("Cost of attending the party");
        money2.setCount("8");
        money2.setMoney("98000");
        List<Money> moneys = new ArrayList<>();
        moneys.add(money1);
        moneys.add(money2);
        // Plug-in binding
        Configure config = Configure.builder()
                .bind("moneys", policy).build();
        String templatePath = "C:/mydata/generator/demo/template.docx";
        XWPFTemplate template = XWPFTemplate.compile(templatePath, config).render(
                new HashMap<String, Object>() {{
                    put("moneys", moneys); }}); String filePath ="C:/mydata/generator/demo/zszxz.docx";
        template.writeToFile(filePath);
        template.close();
    }
Copy the code

Generate results

Apply colours to a drawing list

List template {{*}}

Rendering code

public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();

        params.put("list", Numberings.create("Plug-in grammar"."Supports word text, pictures, table..."."Not just templates"));

        String templatePath = "C:/mydata/generator/demo/template.docx";
        // Generate word path
        String fileDir = "C:/mydata/generator/demo";
        // Generate a word file
        String fileName = "zszxz.docx";

        String wordPath = createWord(templatePath, fileDir, fileName, params);
        System.out.println("Generate document path:" + wordPath);
    }
Copy the code

The renderings

The last

Need this set of tutorial word template concern public number: knowledge seeker reply template to get debugging