一.条件:可根据个人情况更改与下面部分代码结合.
1.建一个test.docx文档.
内容:
另保存为test.xml.重命名为test.ftl.把test.ftl放入项目指定位置.并修改test.ftl.
二.后端实现代码(测试用):
1.word操作工具类.
public class WordUtil {
private static Logger log = Logger.getLogger(WordUtil.class);
/**
* @Desc:生成word文件
* @paramdataMap word中需要展示的动态数据,用map集合来保存
* @paramtemplateName word模板名称,例如:test.ftl
* @paramfilePath文件生成的目标路径,例如:C:/
* @paramfileName生成的文件名称,例如:test.doc
* */
public static void createWord(Map<String, Object>dataMap,String templateName,String filePath,String fileName){
try {
//创建配置实例
Configuration configuration = new Configuration();
//设置编码
configuration.setDefaultEncoding("UTF-8");
//ftl模板文件
/* File file = new File(filePath);
configuration.setDirectoryForTemplateLoading(file);*/
configuration.setClassForTemplateLoading(WordUtil.class,"/templates/generator/");//ftl固定存储位置
//获取模板
Template template = configuration.getTemplate(templateName);
//输出文件
/*File desktopDir = FileSystemView.getFileSystemView() .getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath();
File outFile = new File(desktopPath + File.separator + fileName);//输出到桌面*/
File outFile = new File(filePath + File.separator + fileName);
//如果输出目标文件夹不存在,则创建
if (!outFile.getParentFile().exists()){
outFile.getParentFile().mkdirs();
}
//将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//生成文件
template.process(dataMap, out);
//关闭流
out.flush();
out.close();
} catch (Exception e) {
log.error("生成 word文档(WordUtil)出错:[msg:"+e.getMessage()+"] ,文件名:" + fileName);
e.printStackTrace();
}
}
/** 文件下载
* @param path 文件路径全路径,包含文件名
* @param response
* @return
* */
public static HttpServletResponse downFile(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
String fileName = URLEncoder.encode(filename,"UTF-8");
if(fileName.length()>150){
fileName=new String(filename.getBytes("GBK"),"ISO-8859-1"); }
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Content-Length", "" + file.length());
OutputStream outs = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outs.write(buffer);
outs.flush();
outs.close();
file.delete();
}catch (IOException e) {
log.error("下载文档(WordUtil)出错:[msg:"+e.getMessage()+"] "); e.printStackTrace(); }
return response;
}
}
2.控制层
@RequestMapping("downWord")
public void DownWord(HttpServletRequest request, String response) throws IOException {
List<TrainScore> info = new ArrayList<TrainScore>();
//测试数据,也可以从数据库中提取
for(int i=0;i<3;i++){
TrainScore ts = new TrainScore();
ts.setId("12345667"+i);
ts.setUserId("91345678"+i);
ts.setTrainId("3456789"+i);
ts.setScore(90+i);
ts.setComment("测试"+i);
info.add(ts);
}
Map<String, Object> params = new HashMap<String, Object>();
params.put("title","用户考核表数据");
params.put("info",info);
//我的图片位置images/timg.png
params.put("image",getImageBase("images/timg.png",request));
params.put("attention","请注意确保所有信息的正确性");
WordUtil wordUtil = new WordUtil();
wordUtil.createWord(params,"test.ftl","C:/","test.doc");
}
//获得图片路径和base64编码
private String getImageBase(String src,HttpServletRequest request) {
if(src==null||src==""){
return "";
}
//图片在项目中的路径
File file = new File(request.getSession().getServletContext().getRealPath("/")+src.replace(request.getSession().getServletContext().getContextPath(),""));
if(!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
三.运行结果: