一,首先制作模闆
1.先做一個Word文檔,
2.打開Word,然後另存為*.xml檔案
3.最後修改*.xml檔案的字尾名為*.ftl
二,打開項目編輯器Idea,在pom檔案中引入相關架包依賴(我這裡用的是maven)
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
//下面是gradle的引入格式,可根據自己需要使用相應方式
(compile group: \'org.apache.poi\', name: \'poi\', version: \'3.14\')
三,以上準備完畢開始編寫代碼
以下是接口中應寫内容=>
Map<String, Object> dataMap = new HashMap<String, Object>();
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
configuration.setDefaultEncoding("utf-8");
//得到需要傳入Word檔案中的相關内容資料
//user為資料對象,getUser()為查詢資料的方法,在用的時候換成自己的對應方法即可
User user=useruserService.useruserService.getUser();
if(user.getName()!=null && !user.getName().equals("")){
dataMap.put("name",user.getName());
}
if(user.getSex()!=null && !user.getSex().equals("")){
dataMap.put("sex",user.getSex());
}
if(user.getAge()!=null && !user.getAge().equals("")){
dataMap.put("age",user.getAge());
}
//還有更多屬性...大家可根據自己的實際需求進行添加
//得到模闆位置(因為實際環境中模闆可能較多,是以一般都是有一個專屬的檔案夾用來存放模闆(template))
configuration.setClassForTemplateLoading(this.getClass(), "/template");
Template t = null;
File outFile = null;
//建立一個檔案路徑,用來存放生成的相關檔案
File myFilePath=new File(fileUploadPath+"/projects/"+projectsDto.getId()+"/file/");
if(!myFilePath.exists()){
myFilePath.mkdir();
}
//建立新檔案
String path="../../"+"新檔案.doc";
t=configuration.getTemplate("模闆檔案.ftl","UTF-8");
outFile=new File("../../../"+"新檔案.doc");
Writer out = null;
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// 生成檔案
t.process(dataMap, out);
// 關閉流
out.flush();
out.close();
//path是傳回給前端找到這個檔案的一個路徑
return path;
注:在制作模闆的時候最好在需要傳入值得地方做好标記,這樣在ftl中找對應位置的時候會友善許多
ftl檔案中對應字段屬性位置的格式(name對應代碼中dataMap中相應的鍵值)
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISM9AnYldnJwAzN9c3Pn5GcuQ0MlMWbidXND1UMRpXTzUERPhXWE10dJRUT5hTMORTVT9ENVlnTGZ1USNkVpFVNVNlTGZ1UNJkVpJ1QWNkTGZ1USJkVTJ1QWNlTGZ1UNBzY61UNBR0T4lFRNdXS6hld5MVT0kERNNzYU1kdVhVYxx2VlR3YtJGboJzY2Z0RkZHMyIma5EzYulzRilWNykldwIjYqVTej5WOHJWa1ITW11EWa5mRXJGc5kHT20ESjBjUIF2Lc12bj5SYphXa5VWen5WY35iclN3Ztl2Lc9CX6MHc0RHaiojIsJye.png)