A-A+
生成Word(Java-FreeMaker)
生成Word将分成两篇文章介绍,原理大同小异,主要是使用的模板引擎有所不同,网络上比较多的是如何使用FreeMaker来生成,所以本篇还是基于FreeMaker来简单介绍一下,下一篇将基于Beetl来介绍。
首先,引入FreeMaker(基于Maven):
- <!--freemarker start -->
- <dependency>
- <groupId>org.freemarker</groupId>
- <artifactId>freemarker</artifactId>
- <version>2.3.23</version>
- </dependency>
- <!--freemarker end-->
然后使用将word文件(.doc或.docx)另存为xml文件,并将其中需要动态填充的内容使用FreeMaker的占位符号替换掉,如下:
- <w:r>
- <w:rPr>
- <w:rFonts w:hint="eastAsia"/>
- </w:rPr>
- <w:t>${text1}</w:t>
- </w:r>
然后是一段完整的代码:
- public class FTLExportWord implements IExportWord{
- private static Template t;
- private Configuration createConfig() throws IOException {
- Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
- configuration.setDefaultEncoding("UTF-8");
- configuration.setClassForTemplateLoading(FTLExportWord.class, ConfigConst.TEMPLATE_PACK);
- configuration.setClassicCompatible(true);
- return configuration;
- }
- private Template createTemplate() throws IOException {
- Configuration configuration = createConfig();
- Template template = configuration.getTemplate(ConfigConst.FTL_TEMPLATE_TEST);
- t = template;
- return t;
- }
- public void exportWord(String outPath, Map<String, Object> dataMap) throws Exception {
- if (null == t){
- createTemplate();
- }
- File outFile = new File(outPath);
- if (!outFile.getParentFile().exists()){
- outFile.getParentFile().mkdirs();
- }
- FileOutputStream fos = new FileOutputStream(outFile);
- OutputStreamWriter oWriter = new OutputStreamWriter(fos,"utf-8");
- Writer out = new BufferedWriter(oWriter);
- t.process(dataMap, out);
- }
- }
其中:
- public class ConfigConst {
- public final static String TEMPLATE_PACK = "/com/xnck/demo/exportword/template";
- public final static String BTL_TEMPLATE_TEST = "/template-test.btl";
- public final static String FTL_TEMPLATE_TEST = "/template-test.ftl";
- }
调用的时候:
- Map<String, Object> data = new HashMap<String, Object>();
- data.put("text1", "1111111111111");
- new FTLExportWord().exportWord("C:\\temp\\test.doc", data);