這里springboot項目,模板放在了templates下面,后面要根據模板生成word
1、生成一個word模板,如圖:
注:{{code}}的是需填寫的參數
下面是生成本地的
pom文件:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jcommon</artifactId>
<version>1.0.24</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.0</version>
</dependency>
/**
* @Version 1.0.0
* @Description
*/
public class WordUtil {
/**
* 生成word
* @param templatePath
* @param temDir
* @param fileName
* @param params
*/
public static void exportWord(String templatePath, String temDir, String fileName, Map<String,Object> params){
Assert.notNull(templatePath, "模板路徑不能為空");
Assert.notNull(temDir, "臨時文件路徑不能為空");
Assert.notNull(fileName, "導出文件名不能為空");
Assert.isTrue(fileName.endsWith(".docx"), "word導出請使用docx格式");
if (!temDir.endsWith("/")) {
temDir = temDir + File.separator;
}
File dir = new File(temDir);
if (!dir.exists()) {
dir.mkdirs();
}
try {
XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
String tmpPath = temDir + fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
doc.write(fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @Version 1.0.0
* @Description
*/
public class WordDemo {
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("username", "張三");
map.put("company","xx公司" );
map.put("date","2020-04-20" );
map.put("dept","IT部" );
map.put("startTime","2020-04-20 08:00:00" );
map.put("endTime","2020-04-20 08:00:00" );
map.put("reason", "外出辦公");
map.put("time","2020-04-22" );
WordUtil.exportWord("templates/demo.docx","D:/" ,"生成文件.docx" ,map );
}
}
2、下面是下載word文件
/**
* 導出word形式
* @param response
*/
@RequestMapping("/exportWord")
public void exportWord(HttpServletResponse response){
Map<String,Object> map = new HashMap<>();
map.put("username", "張三");
map.put("company","杭州xx公司" );
map.put("date","2020-04-20" );
map.put("dept","IT部" );
map.put("startTime","2020-04-20 08:00:00" );
map.put("endTime","2020-04-20 08:00:00" );
map.put("reason", "外出辦公");
map.put("time","2020-04-22" );
try {
response.setContentType("application/msword");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("測試","UTF-8" );
//String fileName = "測試"
response.setHeader("Content-disposition","attachment;filename="+fileName+".docx" );
XWPFDocument doc = WordExportUtil.exportWord07("templates/demo.docx",map);
doc.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
//WordUtil.exportWord("templates/demo.docx","D:/" ,"生成文件.docx" ,map );
}