当前位置: 移动技术网 > IT编程>开发语言>Java > 通过freemarker导出word

通过freemarker导出word

2020年07月17日  | 移动技术网IT编程  | 我要评论

通过freemarker导出word

准备步骤

先准备好你的word模板
将word模板中的变量名也就是你想接受的东西,比如姓名以${fdName}这种形式改变,这种键值对形式。

  1. 将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}这种表达式被代码隔开了,比如
在这里插入图片描述

这样一个个被散落了,把中间的代码删掉,重新组成一个fdxx![](https://imgblog.csdnimg.cn/20200715211640775.png)expressionparameters21.word"!{fdxx}的表达式即可。 或者有这个问题 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200715211640775.png) 这种expression parameters的错误,说明后面那个字段得到的是空值,所以传值的时候要做判空处理。 注意事项: 经常出错的2个: 1.导出word的数据不能为空,如果为空的话,需要在变量中添加"!”。 如文件名称为空的话,这样写,{fileName},会造成导出的word打不开,需要这样写,fileName!2.word"""<>"?htmlword{fileName!}。 2.导出word的数据不能有特殊字符,比如"《》" 、"<>"等,如果包含这些字符,需要在变量中添加“?html”。 同样,文件名称中包含特殊字符的话,也会造成导出的word打不开,需要这样写,{fileName?html},也可能文件名称也为空,这时候需要这样写${(fileName?html)!}

本文地址:https://blog.csdn.net/weixin_42765231/article/details/107369971

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网