使用freemarker生成word文档的步骤(当然也可以是别的 比如生成代码之类的,这里以word为例)
1.设计模板(word,可以带图片,可以复杂格式,可以多页)
2.填写参数(使用 ${name} 方式替换需要替换的字段)
3.另存为xml格式文件
4.重命名为ftl后缀格式文件
5.放到项目resource文件夹下(项目中能拿到这个位置即可,springboot为例)
6.代码中使用
具体实现如下:
pom文件
<!-- freemarker --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>java工具类
import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.*; import java.util.Map; public class DocumentHandler { private static Configuration configuration = null; public DocumentHandler() { configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); } public void createDoc(Map<String, Object> objectMap, String dirPath, String filePath, String tempPath) { //要填入模本的数据文件 //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载, //这里我们的模板是放在com.havenliu.document.template包下面 configuration.setClassForTemplateLoading(this.getClass(), "/template"); Template t = null; try { //test.ftl为要装载的模板 t = configuration.getTemplate(tempPath); } catch (IOException e) { e.printStackTrace(); } //输出文档路径及名称 File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } File outFile = new File(filePath); Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile))); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { t.process(objectMap, out); } catch (TemplateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }使用方法
//构造数据 map形式 Map<String, Object> dataMap = Maps.newHashMap(); dataMap.put("name", "张三"); dataMap.put("age", "18"); DocumentHandler documentHandler = new DocumentHandler(); String currDate = DateUtils.getCurrentDateStr("yyyyMMdd"); String dirPath = this.upLoadPath + "/" + "1001002" + "/" + currDate; String _name = "生成的文件名"; String filePath = dirPath + "/" + _name + DateUtils.getCurrentDateStr("yyyyMMddHHmmss") + ".doc"; //模板所在路径 一般放resource文件夹下 String tempPath = "/templ/test.ftl"; documentHandler.createDoc(dataMap, dirPath, filePath, tempPath);
