- 把模板word需要填充的地方写入内容并保存,然后另存为Word 2003 XML 文档(*.xml),把模板放到系统内。
- 根据填充的内容,找到对应的位置,使用<![CDATA[${tml}]]>替代掉填充内容,${tml}就是服务端传回此处内容的key,按照自己的习惯定义即可,<![CDATA[ ]]>的作用主要是防止服务端传参为空,或者没传会报错的问题,如果数据为List则使用list标签遍历,如下:
<w:tc> <w:tcPr> <w:tcW w:w="1256" w:type="dxa"/> </w:tcPr> <#list testMethodList as tml> <w:p wsp:rsidR="002D3582" wsp:rsidRDefault="002D3582" wsp:rsidP="00FE67C7"> <w:pPr> <w:jc w:val="center"/> <w:rPr> <w:sz w:val="22"/> <w:sz-cs w:val="22"/> </w:rPr> </w:pPr> <aml:annotation aml:id="1" w:type="Word.Bookmark.Start" w:name="Col_TestMeth"/> <aml:annotation aml:id="1" w:type="Word.Bookmark.End"/> <w:r> <w:rPr> <w:sz w:val="22"/> <w:sz-cs w:val="22"/> </w:rPr> <w:t><![CDATA[${tml}]]></w:t> </w:r> </w:p> </#list> </w:tc>
特别注意试项:word文档是按列进行数据填充的,所以需要按照列的方式组织数据,但是又要兼顾每一行数据的位置对应
-
文件下载的方式:第一种是使用浏览器下载,代码如下,(参数说明:fileName为模板名称,带后缀;outName为文件输出时的名称,带后缀;writeData为模板中需要填充数据的map)(需要引入freemarker的jar):
-
response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(outName, "UTF-8")); Writer writer = response.getWriter(); Configuration cfg=new Configuration(); String path =FtlHandler.class.getResource("/").getPath()+"ftl"; TemplateLoader templateLoader = new FileTemplateLoader(new File(path)); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8");//设置模板读取的编码方式,用于处理乱码 Template template = cfg.getTemplate(fileName,"UTF-8");//模板文件,支持xml,ftl 也支持html template.process(writeData, writer);//将模板写到文件中 writer.flush(); cfg.clearTemplateCache(); writer.close();
第二种是下载到指定的位置,(参数说明:newTemp.ftl为模板名称;datas为模板中需要填充数据的map):
Configuration cfg = new Configuration(); // 通过Freemaker的Configuration读取相应的ftl TemplateLoader templateLoader = new FileTemplateLoader(new File(AutoDownloadReportService.class.getResource("/").getPath() + "ftl")); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8");// 设置模板读取的编码方式,用于处理乱码 Template template = cfg.getTemplate("newTemp.ftl", "UTF-8");// 模板文件,支持xml,ftl 也支持html File file = new File(path + "\\" + "胶料报告" + gnumber + " " + batch + ".doc"); if (!file.getParentFile().exists()) { // 判断有没有父路径,就是判断文件整个路径是否存在 file.getParentFile().mkdir(); // 不存在就全部创建 } Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); template.process(datas, out); out.flush(); out.close();
使用xml、ftl模板生成word文档,下载到浏览器或指定位置
于 2022-08-05 12:04:38 首次发布