1.用word设置好你需要生成的word模板
2.将word文档设置成.xml格式(注意"${}"符号是否按照规范显示成xml文档)
3.话不多少上代码
//xml文件放至位置
String xmlPath = "G:/report/upload/test.xml";
//word生成位置
String uploadPath="G:/report/upload/";
//word生成名字
String targetName="word.doc";
//获得xml文件夹路径
String templatePath=xmlPath.substring(0,xmlPath.lastIndexOf("/"));
//获得xml名字
String templateName=xmlPath.substring(xmlPath.lastIndexOf("/") + 1, xmlPath.length());
try {
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
//判断生成位置是否存在,不存在则创建
File file = new File(uploadPath);
if (!file.exists()) {
file.mkdirs();
}
// 加载模板数据(从文件路径中获取文件,其他方式)
configuration.setDirectoryForTemplateLoading(new File(templatePath));
Template template = configuration.getTemplate(templateName);
File outFile = new File(uploadPath + File.separator + targetName);
FileOutputStream fileOutputStream = new FileOutputStream(outFile);
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(fileOutputStream, "UTF-8"));
Map dataMap =new HashMap<>();
User user=new User();
user.setName("陈惊");
user.setAge(25);
user.setSex("男");
String text="互相学习过程";
dataMap.put("table",user);
dataMap.put("text",text);
//生成文件
template.process(dataMap, out);
//关闭资源
out.flush();
out.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
4.效果如下



