freemarker在开发中用得较多的是根据模板文件进行动态填充数据,随后导出。
但是在有的业务场景中会使用String作为模板填充数据,如发送短信等。下面介绍使用
public void doWork(){
Map<String, Object> dataModel=new HashMap<String, Object>();
dataModel.put("student", studentService.get(1));
Configuration cf=new Configuration(Configuration.VERSION_2_3_28);
String temName = "testName";
String sourceStr = "你好,我是${student.name}!";
StringWriter out = new StringWriter();//填充数据的结果
Template template=new Template(temName , sourceStr ,cf);
template.process(dataModel, out);
value=out.toString(); //value = 你好,我是小明!
}
结合pageoffice的使用,之前遇到的pageoffice(以word为例)。是一个固定的模板文件,上面插入指定的书签,然后程序猿针对其上的字段进行开发。
后来有一业务场景:模板文件不固定,可以让用户直接上传,修改和更换。书签则让用户自行选择插入。
解决思路: 1. 程序猿需要开发好一些可用的字段作为属性存下来(name: 属性名称, value: freemarker可读的表达式),供用户选择。2.用户上传插好标签的模板文件后,可以在界面中针对该模板文件选择需要的属性(属性和自己插入的标签一一对应起来)。3.填充数据导出文件时,读取该模板配好的属性,找到其value, 使用freemarker把其填充成真实数据 : 如 ${user.name} -- > 小明 . 然后根据用户填写的标签名PO_userName,使用pageoffice进行填充到模板。
下面上代码, 只上赋值的部分, pageoffice读取文件并在线打开的代码省略
public void getValues4Pageoffice(WordDocument doc,String userId,String fileId){
User user=userService.get(userId);
Configuration cf=new Configuration(Configuration.VERSION_2_3_28);
cf.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
//取该模板文件的配置属性
List<OnlineFileAttribute> list = this.pageOfficeService.listAttrByFileId(fileId, null);
Map<String, Object> dataModel=new HashMap<String, Object>();
dataModel.put("user", user);
for (OnlineFileAttribute on : list) {
String value="";
try {
StringWriter out = new StringWriter();
//codeName:如${user.name},code由程序猿开发好作为基础数据让用户选择
Template template=new Template(on.getId(), on.getCodeName(),cf);
template.process(dataModel, out);
value=out.toString();//根据字符串填充
} catch (Exception e) {
e.printStackTrace();
}
//pageoffice根据书签赋值
if (doc!=null) {
DataRegion data = doc.openDataRegion(on.getLableName());//lableName由用户填写
data.setValue(value);
}
}
}