jar 包依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
生成word方法
/**
* 生成 word 文件
*
* @param dataMap 待填充數據
* @param templateName 模板文件名稱
* @param filePath 模板文件路徑
* @param fileName 生成的 word 文件名稱
* @param response 響應流
*/
public static void createWord(Map dataMap, String templateName, String filePath, String fileName, HttpServletResponse response){
// 創建配置實例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
// 設置編碼
configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
// ftl模板文件
configuration.setClassForTemplateLoading(WordUtil.class, filePath);
try {
// 獲取模板
Template template = configuration.getTemplate(templateName);
response.setHeader("Content-disposition",
"attachment;filename=" + URLEncoder.encode(fileName + ".doc", StandardCharsets.UTF_8.name()));
// 定義輸出類型
response.setContentType("application/msword");
Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
// 生成文件
template.process(dataMap, out);
out.flush();
out.close();
} catch (Exception e){
e.printStackTrace();
}
}
數據準備
簡單數據
@RequestMapping("/download")
public void download(HttpServletResponse response) {
Map map = Maps.newHashMap();
map.put("name", "張三");
map.put("age", 20);
map.put("sex","男");
WordUtil.createWord(map, "template.ftl", "/templates/", "測試文件", response);
}
集合數據
若需生成如下格式的 word
freemarker 中對於集合對象的遍歷
<#list userList as user>
...
${user.name}
...
${user.sex}
...
</#list>
如果佔位符是集合類型,需要在 XXX.doc 文件 轉 XXX.ftl 模板文件中修改爲以上格式
集合類型模板數據模擬
@RequestMapping("/download")
public void download(HttpServletResponse response) {
ArrayList<UserInfo> userList = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
UserInfo userInfo = new UserInfo("Jaemon" + i, i % 2, i + 10, "13566321235");
userList.add(userInfo);
}
ArrayList<RoleInfo> roleList = Lists.newArrayList();
roleList.add(new RoleInfo(1L, "管理員", "admin"));
Map<String, Object> map = Maps.newHashMap();
map.put("date", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
map.put("author", "Jaemon");
map.put("userTable","用戶表格");
map.put("userList", userList);
map.put("roleTable","角色表格");
map.put("roleList",roleList);
WordUtils.createWord(map, "template.ftl", "/templates/", "測試文件", response);
}
生成的文件
ftl 模板文件編寫說明
新建 word 文件, 填寫模板內容, 待填充內容使用佔位符 ${key}, 列表使用 ${list.name} , 然後另存爲 .xml 文件, 注意: 檢查 xml 文件中佔位符是否有錯亂, 最後重命名爲 ftl 文件即可
具體詳見: 模板文件生成規則