word document generation scheme

1. Make a freemarker template file

Making a freemarker template file can evolve through these steps:
.doc file –> .xml file –> *.ftl file①
. Use office software to create a new word file, design the format of the file, and use a variable name to occupy the place that needs to be filled with data (no freemarker label here, just use ordinary English words to occupy the place), save. As shown in the figure:
write picture description here

②. Save the word file in the previous step as a file in xml format, as shown in the figure:
write picture description here

③. Use any text editor to open the xml file (because the content of the xml file is relatively complex, it is recommended to use the front-end page editor software such as Hbuilder to open, because the content layout of the file can be beautified, so that it looks more hierarchical), you can see , the variables I set in the first step are reflected in the xml file as follows:
write picture description here

For the inserted picture, the string that has been converted into base64 format by the office software is stored in the package, as shown in the figure:
write picture description here

2. Use the freemarker tag to replace the data model that needs to be populated

Based on the previous step, you need to use the freemarker tag to replace the content that needs to be filled in the call, as shown in the figure:
write picture description here

For pictures, you need to delete the generated string in base64 format, and then replace it with any character variable you want to set, as shown in the figure:
write picture description here

3. Use Java code to complete the generation of the word file (please download the code to view the specific code)

1>.Add jar support
write picture description here
2>.Set the path of the template

public FreemarkerUtils(String encoding) {
        this.encoding = encoding;
        config = new Configuration(Configuration.VERSION_2_3_23);
        config.setDefaultEncoding(encoding);
        config.setClassForTemplateLoading(this.getClass(), "/");
    }

3>. Read the freemarker template to the JVM according to the template path:

private Template getTemplate(String templatePath) {
        Template template = null;
        try {
            template = config.getTemplate(templatePath);
        } catch (TemplateNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("找不到doc模板文件." + e.getMessage());
        } catch (MalformedTemplateNameException e) {
            e.printStackTrace();
            throw new RuntimeException("doc模板文件格式不正确." + e.getMessage());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("doc模板文件解析出错." + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("doc模板文件流读取出错." + e.getMessage());
        }
        return template;
    }

4>. Populate the template with the data model

public void generateFile(String templatePath, String targetPath, Map<String, Object> dataModel) {
        Writer writer = null;
        Template template = null;

        try {
            if (FileUtils.createFile(targetPath)) {// 新建doc文件

                template = getTemplate(templatePath);// 拿模板

                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetPath), encoding));

                // 合成
                template.process(dataModel, writer);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成目标文件出错." + e.getMessage());
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭流失败." + e.getMessage());
            }
        }
    }

Note: In the process of using freemarker to generate word files, you need to pay attention:
1. If there are pictures in the file that need to be inserted, in the process of making the freemarker template, the content of the picture needs to be<pkg:binaryData> </pkg:binaryData>included in the label, otherwise the picture cannot be inserted;
2. Corresponding to , when inserting a picture with Java code, you need toa string in base64 format ; the conversion code is as shown in the figure:

public static String getImageStr(String imgFilePath) {
        InputStream in = null;

        byte[] data = null;

        StringBuilder sb = new StringBuilder();
        try {
            in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();

            sb.append(encoder.encode(data));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325980993&siteId=291194637