1.引入依赖
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2.确认导出模板
将word 修改为xml后缀文件, 再放入编辑器中改为flt后缀文件。
3.导出工具类
public static void writeResponse( HttpServletRequest request, HttpServletResponse response, String version, String docTempDir, String docFileName, String templateDir, String templateFile, Map<String, List<Map<String, Object>>> beanParams) {
Configuration config = new Configuration();
//设置编码
config.setEncoding(Locale.getDefault(), "utf-8");
// ServletContext sc = request.getSession().getServletContext();
InputStream is = null;
File previewFile = null;
try {
//获取模板路径
config.setClassForTemplateLoading(WordExportUtil.class,templateDir);
Template t=null;
try {
t = config.getTemplate("moban.ftl","UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
docFileName = URLEncoder.encode(docFileName, "UTF-8");
if (WORD_2007.equals(version)) {
docFileName = docFileName + ".docx";
// docFileName = encodeFilename(docFileName + ".docx", request);
} else {
docFileName = docFileName + ".doc";
}
String docName = request.getSession().getServletContext().getRealPath("/"+docTempDir)+docFileName;
FileOutputStream fos = new FileOutputStream(docName);
Writer out = new OutputStreamWriter(fos, "UTF-8");
t.process(beanParams, out);
out.flush();
out.close();
previewFile = new File(docName);
is = new FileInputStream(previewFile);
response.reset();
if (WORD_2007.equals(version)) {
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
}else{
response.setContentType("application/vnd.ms-word;charset=UTF-8");
}
response.addHeader("Content-Disposition", "attachment;filename="+docFileName);
byte[] b = new byte[1024];
int len;
while ((len=is.read(b)) >0) {
response.getOutputStream().write(b,0,len);
}
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(previewFile!=null){
previewFile.delete();
}
}
}
4.封装数据调用。数据一定是map<>
WordExportUtil.writeResponse(request, response, WordExportUtil.WORD_2003, "导出文件名", "moban1.ftl", wordmap);
5.替换修改模板
<#list wordlist as map> 取出数据开始循环。
${map.dto.name} 取对象属性
<#list map.dtolist as list> 取map种list 循环
//分页标签
<w:p ><w:r><w:br w:type="page" /></w:r></w:p>
判空以及if else (dto.education)! 判空 如果取不到值就会报错。所以都加上判空
<w:t>大专<#if (dto.education)! =="1"><w:sym w:font="Wingdings 2" w:char="F052"/><#else><w:sym w:font="Wingdings 2" w:char="00A3"/></#if>本科<#if (dto.education)! =="2"><w:sym w:font="Wingdings 2" w:char="F052"/><#else><w:sym w:font="Wingdings 2" w:char="00A3"/></#if> </w:t>