通过freemarker导出word
程序员文章站
2022-10-04 08:32:52
通过freemarker导出word准备步骤上代码问题准备步骤先准备好你的word模板将word模板中的变量名也就是你想接受的东西,比如姓名:${fdName}这种形式改变。这种键值对的形式2. 将word文档用office另存为xml文档,然后再把这个xml文件改变后缀名为ftl格式3.将这个ftl文件放将代码中比如src的某个包下,再将FillDataInWord.java放进想要的放的工具类包中上代码下面是我的FillDataInWord.java的代码`package co...
准备步骤
先准备好你的word模板
- 将word模板中的变量名也就是你想接受的东西,比如姓名:${fdName}
这种形式改变。这种键值对的形式
2 . 将word文档用office另存为xml文档,然后再把这个xml文件改变后缀名为ftl格式
3.将这个ftl文件放将代码中比如src的某个包下,再将FillDataInWord.java放进想要的放的工具类包中
上代码
下面是我的FillDataInWord.java的代码`
package com.landray.kmss.km.agreement.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.compress.utils.ArchiveUtils;
import com.landray.kmss.util.DateUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FillDataInWord {
private Configuration configuration = null;
public FillDataInWord() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
/* luow开始 */
public File createWord(Map<String, Object> mapData, String fileName,String fdAuthType,
HttpServletResponse response)
throws UnsupportedEncodingException, IOException,
FileNotFoundException {
System.out.println(
"=======================替换开始==========================");
configuration.setClassForTemplateLoading(this.getClass(),
"/com/util/");// doc模板的位置
Template template = null;
File outFile = new File(fileName);
try {
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "utf-8"));
if("02".equals(fdAuthType)){
template = configuration.getTemplate("docxBook5.ftl");// 加载word模板
}else{
template = configuration.getTemplate("docxBook9.ftl");// 加载word模板
}
template.setEncoding("utf-8");
template.process(mapData, out);
out.close();
// fos.close();
} catch (TemplateException e) {
e.printStackTrace();
}
System.out.println(
"=======================替换结束==========================");
return outFile;
}
/** * 导出word 并提供下载 * @param response */
public void download(Map<String, Object> mapData, String fileName,String fdAuthType,HttpServletResponse response) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
Date d =new Date();
String date = DateUtil.convertDateToString(d, "yyyy-MM-dd");
String fName="";
try {
File file = createWord(mapData,fileName,fdAuthType,response);//
System.out.println("文件的路径!!!!!!!!!!!!!!!"+file.getAbsolutePath());
response.setContentType("application/msword;charset=utf-8");
fName=URLEncoder.encode(fileName,"UTF-8");
//解决IE和火狐浏览器不兼容,文件名有中文就乱码的问题
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fName);
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[10240];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
// bis.close();
// bos.close();
if(bis != null) bis.close();
if(bos != null) bos.close();
if(file != null) file.delete(); // 删除临时文件
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.再将值存进Map<String, Object> dataMap = new HashMap<String, Object>();中
public ActionForward exportWord(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
TimeCounter.logCurrentTime("Action-exportWord", true, getClass());
KmssMessages messages = new KmssMessages();
String fdApplyId = request.getParameter("fdApplyId");
String type = request.getParameter("Type");
String fdAuthType ="";
Map<String, Object> dataMap = new HashMap<String, Object>();//创建map集合把表单值放进去
KmAgreementSign kms =new KmAgreementSign();
if("view".equals(type)){//当是合同签订view页面时就直接获取签订form
String fdSignId = request.getParameter("fdSignId");
kms = (KmAgreementSign) getSignServiceImp().findByPrimaryKey(fdSignId);
}else{
HQLInfo hqlInfo = new HQLInfo();
String whereBlock = "kmAgreementSign.fdApply.fdId = :applyId";
hqlInfo.setParameter("applyId", fdApplyId);
hqlInfo.setWhereBlock(whereBlock);
List<KmAgreementSign> kmsList = getSignServiceImp().findList(hqlInfo);
if(!ArrayUtil.isEmpty(kmsList)){
kms = kmsList.get(0);//读取当前合同签订form
}
}
fdAuthType = kms.getFdAuthType();
String fdClientMan = kms.getFdContbody()==null?"":kms.getFdContbody().getFdName();
SysOrgElement authName = kms.getFdAuthPerson();
String fdAuthName = authName.getFdName();
String fdDutyMan = fdAuthName==null?"":fdAuthName;
String fdJob = kms.getFdAuthStation()==null?"":kms.getFdAuthStation();
String fdClientOffice = kms.getFdContbodyed()==null?"":kms.getFdContbodyed().getFdName();
SysOrgElement authedName = kms.getFdAuthedPerson();
String fdAuthedName = authedName.getFdName();
String fdDutyMan2 = fdAuthedName==null?"":fdAuthedName;
String fdJob2 = kms.getFdAuthedStation()==null?"": kms.getFdAuthedStation();
String fdItem = kms.getFdAuthName()==null?"":kms.getFdAuthName();
Date startTime = kms.getFdAuthStart();
String fdExpireDate = kms.getFdAuthContent()==null?"":kms.getFdAuthContent();
dataMap.put("fdExpireDate", fdExpireDate);
Date d =new Date();
String year = DateUtil.convertDateToString(d, "yyyy");
String month = DateUtil.convertDateToString(d, "MM");
String day = DateUtil.convertDateToString(d, "dd");
String date = DateUtil.convertDateToString(d, "yyyy-MM-dd");
dataMap.put("fdClientMan", fdClientMan);
dataMap.put("fdDutyMan", fdDutyMan);
dataMap.put("fdJob", fdJob);
dataMap.put("fdClientOffice",fdClientOffice);
dataMap.put("fdDutyMan2", fdDutyMan2);
dataMap.put("fdJob2", fdJob2);
dataMap.put("fdItem", fdItem);
dataMap.put("fdYear", year);
dataMap.put("fdMonth", month);
dataMap.put("fdDay", day);//以上都是按键值对形式将读取的值存入模板对应位置中
FillDataInWord w = new FillDataInWord();
FileSystemView fsv = FileSystemView.getFileSystemView();
File com=fsv.getHomeDirectory();//获取桌面根路径
String savePath = com.getPath();
// String fileName=savePath+"/授权书"+date+".doc";//通过流形式下载 默认下载到当前桌面
String fileName = "授权委托书"+date+".doc";
/*= "C:/授权书"+date+".doc";*/
w.download(dataMap,fileName ,fdAuthType,response);//输出文件的位置与名字
TimeCounter.logCurrentTime("Action-exportWord", false, getClass());
return null;
}```
这样存放,最后调用FillDataInWord中的createWord方法,
问题
如果报错
这样的错误,一般是ftl文件中有多余代码,先将ftl中的代码放进这个网址https://tool.oschina.net/codeformat/xml/
进行格式化,然后看有没有${fdxxx}这种表达式被代码隔开了,比如
这样一个个被散落了,把中间的代码删掉,重新组成一个{fileName},会造成导出的word打不开,需要这样写,{fileName?html},也可能文件名称也为空,这时候需要这样写${(fileName?html)!}
本文地址:https://blog.csdn.net/weixin_42765231/article/details/107369971