1、将要导出的word文档另存为xml格式的
2、用文档编辑器打开(如:notepad++),将要展示的数据用${name}的形式替换,“name”对应数据库中的字段
3、根据模板生成
package com.idcsol.apps.common.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class DocumentHandler {
private Configuration configuration = null;
public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
public void createDoc(Map<String,Object> dataMap,String fileName,
String tempName) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
configuration.setClassForTemplateLoading(this.getClass(), "/com/idcsol/apps/controller/positionSet/template");
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate(tempName);
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("---------------------------");
}
}
4、控制器中使用
DocumentHandler mdoc = new DocumentHandler ();
String resourcepath = "文件名.doc";
mdoc.createDoc(dataMap, resourcepath,"remoceApplyOut.ftl");
5、通过上述实现,word文档已经导出到服务器上,但是,一般会需要把文件下载到客户机上
实现代码:
package com.idcsol.apps.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import com.idcsol.base.common.constant.BaseConst;
import com.idcsol.base.common.utils.StringUtil;
public class UploadUtil {
private static Log log = LogFactory.getLog(UploadUtil.class);
/**
* 上传文件(下载文件的话不需要该方法)
* @param file
* @return 文件在服务器的相对路径
*/
public static String uploadFile(MultipartFile file) {
String url = "";
String path = "/upload";
try {
// 获取绝对路径
String realPath = com.idcsol.apps.common.constant.Const.REAL_PATH + path;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
String date = df.format(new Date());
realPath = realPath + "/" + date;
// 创建文件夹
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 构建文件名
String fileName = "" + new Date().getTime();
int ext = 0;
if ((ext = file.getOriginalFilename().lastIndexOf(".")) != -1) {
// 扩展名
fileName += file.getOriginalFilename().substring(ext);
}
path = path + "/" + date + "/" + fileName; // 相对路径
url = realPath + "/" + fileName;
file.transferTo(new File(url));
} catch (Exception e) {
log.error(StringUtil.getExceptionDetail(e));
return "";
}
return path;
}
public static void downloadFile(String resourcepath,String filename, HttpServletRequest request,
HttpServletResponse response) {
// String[] fileName1=resourcepath.split("/");
// String fileName=fileName1[fileName1.length-1];
FileInputStream fis = null;
OutputStream out = null;
if(StringUtil.isNotEmpty(filename) && StringUtil.isNotEmpty(resourcepath)) {
try {
//fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF");
realPath=realPath.replace("\\hrm\\WEB-INF","");
realPath.trim();
fis = new FileInputStream(new File(resourcepath));
//设置响应头和保存文件名
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=" + filename);
//写出流信息
int b = BaseConst.ZERO;
out = response.getOutputStream();
byte [] buf = new byte[1024];
while(-1 != (b = fis.read(buf))) {
out.write(buf,0,b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
6、控制器中调用下载的方法
UploadUtil.downloadFile(resourcepath, Docname, request, response);//文件路径、文件名
7、如果导出的文件在服务器上没有必要留下来的话,可以将对应文件删除
public boolean delDoc(HttpServletRequest request ,HttpSession httpSession,
String docName) throws UnsupportedEncodingException {
Result<Object> result = new Result<Object>();
String docname=docName;
// System.out.println(docname+"docname");
String lj= request.getRealPath("/")+docname;
boolean flag = false;
File file = new File(lj);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
/* if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(lj);
}*/ /*else { // 为目录时调用删除目录方法
return deleteDirectory(lj);
} */
deleteFile(lj);
}
return flag;
}
private boolean deleteFile(String lj) {
// TODO Auto-generated method stub
boolean flag = false;
File file = new File(lj);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
// System.out.println("删除成功");
flag = true;
}
return flag;
}
8、控制器中调用删除文件的方法
delDoc(request,httpSession,Docname);
需要导入freemarker的jar包
maven pom.xml的写法
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>
(导出word文档的方法完)