1.maven依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.22</version></dependency>
2.Word模板
Word模板打开,另存为*.xml,然后将文件原封不动的粘贴到resources包下的docXml文件夹中(注意:不可打开xml文件,直接粘贴进去即可)
3.代码
(1)xml文件的位置
(2)导出Word的工具类Util
package com.lanjingjr.console.datuminfo.controller;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class ExportWordUtilDemo {
//读取配置文件
private static Configuration configuration = null;
private static Map<String,Template> allTemplate = null;
private static final String TEMPLATE_PATH = "/docXml"; // 模板加载路径
private static final String DEFAULT_ENCODING = "UTF-8"; // 模板解析编码
static{
configuration = new Configuration(Configuration.VERSION_2_3_22);
//设置编码
configuration.setDefaultEncoding(DEFAULT_ENCODING);
//按照路径加载模板
configuration.setClassForTemplateLoading(ExportWordUtilDemo.class, TEMPLATE_PATH);
//存储模板
allTemplate = new HashMap<String,Template>();
try{
//按照指定编码读取文档
allTemplate.put("paymentNoticeTemplate", configuration.getTemplate("noticeTemplet.xml",DEFAULT_ENCODING));
}catch(IOException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
private ExportWordUtilDemo(){
}
/**
* 创建doc文档
* @param dataMap
* @param type
* @return
*/
public static File createDoc(Map<?,?> dataMap,String type){
//文件名
String name = "temp" + (int)(Math.random()*100000) + ".doc";
File file = new File(name);
//获取模板
Template t = allTemplate.get(type);
try{
//这个地方不能使用FileWriter因为需要指定编码类型否则声场的word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(file),DEFAULT_ENCODING);
t.process(dataMap,w);
w.flush();
w.close();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
return file;
}
}
其中特别注意,UTF-8必须要写,尤其是读取Template模板的时候,否则声称的word文档会显示xml,而不是你要的结果
(3)Controller方法调用,生成Word文档
@RequestMapping("exportPaymentNotice.do")
public void exportPaymentNotice(HttpSession session) throws IOException, TemplateException {
User user = this.getCurrentUser(User.class, session);
// 要填入模本的数据文件
Map dataMap = new HashMap();
dataMap.put("userName", "你好");
dataMap.put("borType", "你好");
dataMap.put("borAmount", "50000");
dataMap.put("platformFee", "50000");
dataMap.put("loanInterest", "50000");
dataMap.put("borTime", "50000");
dataMap.put("dealTime", "50000");
dataMap.put("repaymentType", "50000");
dataMap.put("totalCost", "50000");
//提示:在调用工具类生成Word文档之前应当检查所有字段是否完整
//否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错,这里暂时忽略这个步骤
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try{
//调用工具类WordGenerator的createDoc方法生成Word文档
file = ExportWordUtil.createDoc(dataMap, "paymentNoticeTemplate");
fin = new FileInputStream(file);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/msword");
response.addHeader("Content-Disposition", "attachment;filename=resume111.doc");
out = response.getOutputStream();
byte[] buffer = new byte[1024];//缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
out.flush();
}catch(Exception ex){
ex.printStackTrace();
}
finally{
if(fin != null) fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
}
}