Freemaker generates word templates
1, Introduce dependency
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency>
2, Tool class
Note: for the attribute of Configuration configuration, in some cases, the file grammar will be opened because the parameters are wrong.
package com.dameng.util; import com.dameng.domain.FreemarkerDemo; import freemarker.cache.ClassTemplateLoader; import freemarker.core.XMLOutputFormat; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; import freemarker.template.Version; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Locale; import java.util.Map; /** * Word Document tool class */ public class WordUtil { /** * Automatically generate Word documents using FreeMarker * @param dataMap Data required to generate Word documents * @param fileName The full path name of the generated Word document */ public static void generateWord(Map<String, Object> dataMap, String fileName) throws Exception { // Set the version and encoding format of FreeMarker Configuration configuration = new Configuration(Configuration.VERSION_2_3_27); configuration.setEncoding(Locale.getDefault(),"UTF-8"); configuration.setDefaultEncoding("UTF-8"); configuration.setOutputFormat(XMLOutputFormat.INSTANCE); //Set the exception handler so that there will be no error even if there are no attributes, such as ${list.name} No error will be reported configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); // //Set the path of the template required by FreeMarker to generate Word documents configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerDemo.class,"/templates/")); // Set the template required by FreeMarker to generate Word documents ///Template t = configuration.getTemplate("check_freework202202262238.ftl"); Template t = configuration.getTemplate("check_freework202203061.ftl"); // Create an output stream of a Word document Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "UTF-8")); //FreeMarker uses Word templates and data to generate Word documents t.process(dataMap, out); out.flush(); out.close(); } }
3, Entity class
package com.dameng.domain; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public class FreemarkerDemo { public static void main(String[] args) throws IOException, TemplateException { /*Initialize freemaker template*/ Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); configuration.setDefaultEncoding(Charset.forName("UTF-8").name()); //If the basePackagePath of the ClassTemplateLoader here starts with / is the absolute path. If not / the beginning is relative to //com.saoft.fastdemo.gen.FreemarkerDemo. The relative path of the Java class will be expressed as com saoft. fastdemo. Gen this directory starts to find //FileTemplateLoader configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerDemo.class,"/templates/")); //Get template Template template = configuration.getTemplate("ssm/demo.ftl"); //Data to be injected Map<String, Object> dataMap = new HashMap<>(); dataMap.put("testKey", "This is key"); //The output position is output by string here. If you want to output the file, replace it by yourself StringWriter writer = new StringWriter(); template.process(dataMap, writer); System.out.println(writer.getBuffer()); } }
4, main method
public static void main(String[] args) { Map<String, Object> wordDataMap = getWordData(dataSource,systemInfo); //Output overview information wordDataMap.put("systemInfo",systemInfo); wordDataMap.put("dbSummaryInfo",dbSummaryInfo); WordUtil.generateWord(wordDataMap,generateFileName); }
Note: the FreemarkerDemo class specifies the location of the template.
5, Options for docx documents
6, Trample pit
6.1 special symbols
When using FreeMarker template to generate Word document, if the filled data string contains special characters <, >, &, the generated Word document cannot be opened. Because these characters are considered as labels of FreeMarker template when generating Word document. If these characters are directly used to generate Word document without processing, an error will be reported when opening the generated document with Word, but when opening it with xml, it will be found that all contents are complete, except the above three special characters. Therefore, these three special characters need to be processed when processing data.
6.2 line breaks
When using FreeMarker template to generate Word document, if the filled data string is too long and "\ n" is used for line wrapping, the generated Word document does not play the role of line wrapping. You need to replace "\ n" with "< W: P > < / W: P >", and then use the replaced string data to generate Word documents, so as to achieve the effect of line wrapping.
6.3 the content is in xml format
The content of the Word document generated by this method is essentially in xml format. Therefore, the generated Word document can be opened by Word or xml document tool. If you use a Java program to read the content of the generated Word document, you will also read the content in xml format. If you want to convert the content to Word format, you can use Word to open the generated document and save it as Word document format.
6.4 the suffix is doc
The suffix of Word document generated by this method must be doc format, not docx format, otherwise the generated Word document cannot be opened. If you want to convert suffixes to docx format, you can use Word to open the generated document and then save it as Word document format.
6.5 generate xml and open the encrypted format
This is because notepad + + lacks an xml plug-in, so it is encrypted when opened. Open with notepad or in IDEA
data
https://blog.csdn.net/weixin_44516305/article/details/88049964