第一步:引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
第二步:生成工具类
在util包里生成word工具类=>WordUtils
public class WordUtils {
/**
* 生成 word 文档方法
*
* @param dataMap 要填充的数据
* @param templateName 模版名称
* @param fileName 要输出的文件路径
* @throws Exception 抛出的异常
*/
public static void generateWord(Map<String, Object> dataMap, String templateName, String fileName) throws Exception {
// 设置FreeMarker的版本和编码格式
Configuration configuration = new Configuration(new Version("2.3.28"));
configuration.setDefaultEncoding("UTF-8");
// 设置FreeMarker生成Word文档所需要的模板的路径
// configuration.setDirectoryForTemplateLoading(new File("/Users/xxx/Desktop/"));
// 此处把word转成的ftl模版文件都放在 resources 下的 templates文件夹中
configuration.setClassForTemplateLoading(WordUtils.class, "/templates");
// 设置FreeMarker生成Word文档所需要的模板
Template tem = configuration.getTemplate(templateName, "UTF-8");
// 创建一个Word文档的输出流
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));
// FreeMarker使用Word模板和数据生成Word文档
tem.process(dataMap, out);
out.flush();
out.close();
}
第三步:制作word模板(写好word文件,转成ftl文件)
制作教程
https://jingyan.baidu.com/article/3aed632e4261a3311080919c.html
第四步:把ftl文件放入 resources 下的 templates文件夹中
第五步 :实际应用
新new一个map,存的是ftl(word文件)里需要填入从数据库里查出来的字段部分;
key是ftl文件里的${}部分,value是需要替换的数据;
例如${student1Name},工具会去map里找key为student1Name的键值对,将其对应的值替换进去;
//这个map存的是ftl(word文件)里需要填入从数据库里查出来的字段部分
//key是ftl文件里的${}部分,value是需要替换的数据
//例如${student1Name},工具会去map里找key为student1Name的键值对,将其对应的值替换进去
Map<String, Object> dataMap = new HashMap<>()
//例如studentList是从数据库里查出来的
List<student> studentList = new ArrayList<>();
for (int i = 0; i < studentList.size() ; i++) {
dataMap.put("student1Name", studentList(i).getName());
dataMap.put("student2Name", studentList(i).getName());
dataMap.put("student3Name", studentList(i).getName());
}
//写出word文件
WordUtils.generateWord(dataMap,"student.ftl","E:\\workSpace\\学生名称.doc");
//如果前端下载需要后端返回这个word文件,可以生成一个file路径,使用FileUtil工具返回到前端(FileUtil在另一篇)
//File file = new File("E:\\workSpace\\学生名称.doc");
//FileUtil.downloadFile(request, response,file , false);
如果前端下载需要后端返回这个word文件,可以生成一个file路径,使用FileUtil工具返回到前端(FileUtil在另一篇)