JAVA利用FreeMarker生成(导出)Word文档
- 首先下载相应的jar包:freemarker.jar
自定义Word模板,将需要填入数据的空格使用“${xxx}”替换,另存为.XML文件
图1
另存为xml格式如下:
图2
- 使用编辑器打开XML文件,使用在线XML格式化美化下XML代码,网址如:http://web.chacuo.net/formatxml,然后检查${xxx}是否被分开了(如果被分开删除其中间的代码让他们合并在一起),以及保证此标签的前后无空格(如果有空格将其删除),如果涉及一些需要循环或者复选框之类的再进行网上查阅相关资料,使用freemarker中对应的标签进行实现。
- 编辑完成后,把文件后缀名修改成“.ftl”格式(直接使用xml格式也是可以的,但是如果涉及到使用了freemarker标签等就必须需要使用ftl格式)。
-
代码实现Word文档的生成(导出)
- 准备模板文件
/**
* 准备导出模板
* @author HuangHua
* @param templateFile 模板文件
* @return
* @throws Exception
*/
public Template readyTemplate(String templateFile) throws Exception{
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8"); // 注意这里要设置编码
//加载模板文件,放在/WebContent/file下
configuration.setClassForTemplateLoading(this.getClass(), "/com/kedacom/pms/team/file");
Template temp = null;
try {
// 文件名,还有这里要设置编码
temp = configuration.getTemplate(templateFile, "utf-8");
return temp;
} catch (Exception e) {
throw new Exception(e);
}
}
|
- 读取业务数据
/**
* 导出体能训练文件
* @author HuangHua
* @param fitnesstest 体能训练
* @param scoreList 科目成绩列表
* @param templateFile 模板文件
* @param targetFile 输出文件
* @return
* @throws Exception
*/
public File exportFitnesstestWord(Fitnesstest fitnesstest, List<FitnesstestScore> scoreList, String templateFile, String targetFile) throws Exception {
// 第一步:准备导出模板
Template temp = this.readyTemplate(templateFile);
// 第二步:读取数据
if (fitnesstest != null) {
Map<String, Object> dataMap = new HashMap<String, Object>();
。。。。。。
// 第三步:写文件
File file = DocUtil.exportDoc(temp, dataMap, targetFile);
return file;
} else {
return null;
}
}
|
- 根据业务数据编写生成文件工具类(DocUtil类)
/**
* 根据模板导出doc文档
* @author HuangHua
* @param temp 导出模板
* @param dataMap 数据内容
* @param targetFile 输出文件
* @return
*/
public static File exportDoc(Template temp, Map<String,Object> dataMap, String targetFile) {
File outFile = null;
Writer out = null;
try {
outFile = File.createTempFile(targetFile, ".doc");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
} catch (Exception e1) {
e1.printStackTrace();
}
try {
temp.process(dataMap, out);
} catch (Exception e) {
e.printStackTrace();
}
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
|
- 将业务数据写入文件
- 控制层做出请求响应
/**
* 导出体能训练成绩信息
* @author HuangHua
* @return
*/
public void exportFitnesstest(){
try {
HttpServletResponse response = ServletActionContext.getResponse();
String targetFile = "体能达标成绩表";
File sourceFile = fitnesstestService.exportFitnesstestFile(fitnesstestId,targetFile);
this.responseFile(response, sourceFile, targetFile);
} catch (Exception e) {
log.error("exportLawLevel failed", e);
}
}
/**
* 导出文件响应
* @author HuangHua
* @param response
* @param sourceFile 源文件
* @param targetFile 输出文件
*/
private void responseFile(HttpServletResponse response,File sourceFile,String targetFile){
InputStream fis = null;
OutputStream toClient = null;
try {
fis = new BufferedInputStream(new FileInputStream(sourceFile));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header,这里要用URLEncoder转下才能正确显示中文名称
targetFile = URLEncoder.encode(targetFile, "utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + targetFile+".doc");
response.addHeader("Content-Length", "" + sourceFile.length());
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/msword");
toClient.write(buffer);
toClient.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(fis!=null){
fis.close();
}
if(toClient!=null){
toClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|