步骤一:
首先自己建立一个word文档, 然后另存为: xml (敲重点:一定要另存为,选择XML格式,如果直接在桌面改变文件类型会无效)
步骤二:
把相应的模板文件 改变后缀为 ” 模板名字.ftl ” 在项目中新建文件夹保存到项目中。
步骤三:调用工具类,读取模板文件,并生成需要的word模板
public class WordGenerator2 {
private static Configuration configuration = null;
private static Map<String, Template> allTemplates = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(WordGenerator2.class, "/wordTempl");
allTemplates = new HashMap<>(); // Java 7 钻石语法
try {
allTemplates.put("回执模板", configuration.getTemplate("回执模板.ftl"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private WordGenerator2() {
throw new AssertionError();
}
public static File createDoc(Map<?, ?> dataMap, String type) {
String name = "回执模板" + (int) (Math.random() * 100000) + ".doc";
File f = new File(name);
Template t = allTemplates.get(type);
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;
}
}
===上面是工具类, 下面是工具类的实际应用==web项目浏览器请求响应===
public void ReceiptListDownLoad(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Map<String, Object> map = new HashMap<String, Object>();
Enumeration<String> paramNames = request.getParameterNames();
// 通过循环将表单参数放入键值对映射中
while(paramNames.hasMoreElements()) {
String key = paramNames.nextElement();
String value = request.getParameter(key);
map.put(key, value);
}
// 提示:在调用工具类生成Word文档之前应当检查所有字段是否完整
// 否则Freemarker的模板殷勤在处理时可能会因为找不到值而报错 这里暂时忽略这个步骤了
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
try {
// 调用工具类WordGenerator的createDoc方法生成Word文档
file = WordGenerator2.createDoc(map, "HuiZhiTemp");
fin = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
//输出中文,非常重要
String uncod=URLDecoder.decode("验收模板.doc","UTF-8");
String fileName = new String(uncod.getBytes("UTF-8"), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(fileName)));
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件默认名为resume.doc
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (IOException ie) {
// // TODO Auto-generated catch block
ie.printStackTrace();
}finally {
if(fin != null)
try {
fin.close();
if(out != null) out.close();
if(file != null) file.delete(); // 删除临时文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}