一、模版的设置
1.新建word文档,ctrl + F9 会出现一个域,如图所示。
2.右键选择编辑域,如下图所示。
3.选择邮件合并,前面的不要删除,空格填写${},${}里面写你想要设置的变量名(例如,我这里写的是date),点击确定即可,如图所示。
二、java代码的编写
//获取模板文档
public void getTempFile(Map map, List<Map> titleList) throws IOException, XDocReportException {
//获取Word模板,模板存放路径在项目的resources目录下
InputStream ins = new FileInputStream(此处填写你的模版路径);
//注册xdocreport实例并加载FreeMarker模板引擎
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins,
TemplateEngineKind.Freemarker);
IContext context = report.createContext();
//此处的date是模版里写好的变量,后面是要替换的数据,如果有需要这里的数据可以从数据库查出来在放到/ 这里赋值
context.put("date", “2023-03-03”);
Calendar calendar = Calendar.getInstance();
// 获取当前年
int year = calendar.get(Calendar.YEAR);
// 获取当前月
int month = calendar.get(Calendar.MONTH) + 1;
// 获取当前日
int day = calendar.get(Calendar.DATE);
// 获取当前小时
int hour = calendar.get(Calendar.HOUR_OF_DAY);
// 获取当前分钟
int minute = calendar.get(Calendar.MINUTE);
// 获取当前秒
int second = calendar.get(Calendar.SECOND);
//输出的文件名称
String fileName = year + month + day + hour + minute + second + "0" + ".docx";
//如果需要使用文件路径,可以返回这个filePath,不需要也可以删除
String filePath = getTempPath() + fileName;
//输出到本地目录
FileOutputStream out = new FileOutputStream(new File(filePath));
report.process(context, out);
}
更多模版的书写可以搜索一下Freemarker模版的语法。以上就是模版导出的简单心得,请多指教!