分为两个部分:
1.生成word文档(略去生成模板文件过程)
2.发送至客户端
private boolean createDoc(Map<String, String> map, String filePath,
String fileName) {
boolean createFlag = false;
Template temp = null;
File docFile = null;
Writer docout = null;
try {
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("utf-8");
cfg.setDirectoryForTemplateLoading(new File(filePath));
cfg.setObjectWrapper(new DefaultObjectWrapper());
temp = cfg.getTemplate("123.ftl");
temp.setEncoding("utf-8");
docFile = new File(filePath + "/" + fileName);
docout = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(docFile)));
temp.process(map, docout);
createFlag = true;/
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (TemplateException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (docout != null) {
try {
docout.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return createFlag;
}
private void deleteFile(String filePath, String fileName) {
Log.info("delete start~~~~~~~~~~~~~");
File docFile = null;
docFile = new File(filePath + "/" + fileName);
if (docFile.exists() && docFile.isFile()) {
docFile.delete();
}
Log.info("delete over~~~~~~~~~~~~~");
}
private void downloadFile(String filePath, String fileName,
HttpServletResponse response) {
Log.info("download start~~~~~~~~~~~~~");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
String fileShowName = "test.doc";
response.setContentType("application/msword");
response.setHeader("Content-disposition", "inline;filename="
+ fileShowName);
fis = new FileInputStream(filePath + "/" + fileName);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[100 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
发送至客户端打开方式在上述代码的response.setHeader()中设置。