一、文章背景
公司的某個需求,需要根據(jù)接口的信息生成一份word接口文檔信息并支持導(dǎo)出功能。以前沒做過這種需求,于是搜羅各種資料,最終發(fā)現(xiàn)java利用freemarker模版可以實現(xiàn)這個功能。
二、實現(xiàn)步驟
1、需要的環(huán)境
<!--springboot父依賴-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--springboot啟動器依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--freemarker依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、創(chuàng)建模板
1)展示word文檔如下所示:
2)將word文檔動態(tài)的參數(shù)替換成占位符,如下所示:
3)word另存為xml格式保存
4)將xml文件更改為ftl文件
3、書寫java類
1)將上一步生成的ftl文件重命名cdsnUser.ftl放到resource目錄的templates文件夾下面,并格式化文件
ps:
1.1)因用戶列表是list集合遍歷的形式動態(tài)展示,所以需要遍歷列表標(biāo)簽并展示數(shù)據(jù)。遍歷的語法如下:<#list 集合 as 對象名> </#list>
1.2)注意此處對象別名要和生成word占位符的屬性對應(yīng)上,不然取不到值
1.3)標(biāo)簽是行的意思,遍歷的范圍要對,不然word打不開或者后臺報錯
2)新建User類
import lombok.Data;
@Data
public class User {
private String name;
private String sex;
private String iphone;
private String idcard;
private String idNum;
}
3)wordUtil工具類
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
public class WordUtil {
//配置信息,代碼本身寫的還是很可讀的,就不過多注解了
private static Configuration configuration = null;
// 這里注意的是利用WordUtils的類加載器動態(tài)獲得模板文件的位置
//private static final String templateFolder = wordUtils.class.getClassLoader().getResource("../../../../templates").getPath();
private static final String templateFolder = WordUtil.class.getResource("/templates").getPath();
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
try {
System.out.println(templateFolder);
configuration.setDirectoryForTemplateLoading(new File(templateFolder));
} catch (IOException e) {
e.printStackTrace();
}
}
private WordUtil() {
throw new AssertionError();
}
/**
* 導(dǎo)出excel
* @param request 請求對象
* @param response 響應(yīng)對象
* @param map word文檔中參數(shù)
* @param wordName 為模板的名字 例如xxx.ftl
* @param fileName 是word 文件的名字 格式為:"xxxx.doc"
* @param name 是臨時的文件夾米名稱 string類型 可隨意定義
* @throws IOException
*/
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map, String wordName, String fileName, String name) throws IOException {
Template freemarkerTemplate = configuration.getTemplate(wordName);
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 調(diào)用工具類的createDoc方法生成Word文檔
file = createDoc(map,freemarkerTemplate,name);
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-download");
fileName = new String(fileName.getBytes(), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(fileName)));
out = response.getOutputStream();
byte[] buffer = new byte[512];// 緩沖區(qū)
int bytesToRead = -1;
// 通過循環(huán)將讀入的Word文件的內(nèi)容輸出到瀏覽器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} finally {
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete();// 刪除臨時文件
}
}
private static File createDoc(Map<?, ?> dataMap, Template template, String name) {
File f = new File(name);
Template t = template;
try {
// 這個地方不能使用FileWriter因為需要指定編碼類型否則生成的Word文檔會因為有無法識別的編碼而無法打開
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
}
4)Controller類
import com.example.word_download.dao.InterfaceWord;
import com.example.word_download.dao.Parameter;
import com.example.word_download.dao.User;
import com.example.word_download.util.WordUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/testControllerDownload")
public class wordController {
/**
* 測試用戶列表word的初級
* @param request
* @param response
* @throws IOException
*/
@GetMapping("/getWord")
public void getWord(HttpServletRequest request, HttpServletResponse response) throws IOException {
User user1 = new User();
user1.setName("lisa");
user1.setSex("girl");
user1.setIphone("1243435512434");
user1.setIdcard("4211821997909021");
user1.setIdNum("12");
User user2 = new User();
user2.setName("tom");
user2.setSex("boy");
user2.setIphone("1243435512434");
user2.setIdcard("4211821997909021");
user2.setIdNum("12");
ArrayList<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
//HashMap<String, List<User>> map1 = new HashMap<>();
HashMap<String, Object> map = new HashMap<>();
map.put("users",users);
map.put("appName","用戶信息");
String wordName = "csdnUser.ftl";
String fileName = "interfaceWord.doc";
String name = "name";
WordUtil.exportMillCertificateWord(request,response,map,wordName,fileName,name);
}
}
4、測試
1)啟動springboot項目后,在瀏覽器地址欄中輸入請求路徑,即可生成word文檔并下載。
2)word文檔內(nèi)容如下:
三、freemarker技術(shù)點
1、簡介
FreeMarker是一款模板引擎: 即一種基于模板和要改變的數(shù)據(jù), 并用來生成輸出文本(HTML網(wǎng)頁、電子郵件、配置文件、源代碼等)的通用工具。 它不是面向最終用戶的,而是一個Java類庫,是一款程序員可以嵌入他們所開發(fā)產(chǎn)品的組件。
2、常用語法
1、判斷語法
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
<#else>
...
</#if>
=========================ps:if 空值判斷===========================
// 當(dāng) photoList 不為空時
<#if photoList??>...</#if>
2、遍歷語法
<#list empList! as emp>
${emp.name!}
</#list>
3、某些標(biāo)簽的意思
<w:tr>:行的標(biāo)簽
<w:tbl>:表格的標(biāo)簽
ps:了解某些特定標(biāo)簽在遍歷的時候很方便排錯
4、常見問題文章來源:http://www.zghlxwxcb.cn/news/detail-562242.html
1)如下,獲取值沒有進(jìn)行空值判斷,加入空值判斷就可以去除,如2中空值語法判斷所示。
2、生成word打不開,是標(biāo)簽或者遍歷的位置加入不對,導(dǎo)致word文件異常。文章來源地址http://www.zghlxwxcb.cn/news/detail-562242.html
到了這里,關(guān)于JAVA利用Freemarker模版動態(tài)生成并導(dǎo)出word文檔(全網(wǎng)最詳細(xì))的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!