通过freemarker导出word

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

这样一个个被散落了,把中间的代码删掉,重新组成一个 f d x x 的 表 达 式 即 可 。 或 者 有 这 个 问 题 这 种 e x p r e s s i o n p a r a m e t e r s 的 错 误 , 说 明 后 面 那 个 字 段 得 到 的 是 空 值 , 所 以 传 值 的 时 候 要 做 判 空 处 理 。 注 意 事 项 : 经 常 出 错 的 2 个 : 1. 导 出 w o r d 的 数 据 不 能 为 空 , 如 果 为 空 的 话 , 需 要 在 变 量 中 添 加 " ! ” 。 如 文 件 名 称 为 空 的 话 , 这 样 写 , {fdxx}的表达式即可。 或者有这个问题 这种expression parameters的错误, 说明后面那个字段得到的是空值,所以传值的时候要做判空处理。 注意事项: 经常出错的2个: 1.导出word的数据不能为空,如果为空的话,需要在变量中添加"!”。 如文件名称为空的话,这样写, fdxxexpressionparameters21.word"!{fileName},会造成导出的word打不开,需要这样写, f i l e N a m e ! 。 2. 导 出 w o r d 的 数 据 不 能 有 特 殊 字 符 , 比 如 " 《 》 " 、 " < > " 等 , 如 果 包 含 这 些 字 符 , 需 要 在 变 量 中 添 加 “ ? h t m l ” 。 同 样 , 文 件 名 称 中 包 含 特 殊 字 符 的 话 , 也 会 造 成 导 出 的 w o r d 打 不 开 , 需 要 这 样 写 , {fileName!}。 2.导出word的数据不能有特殊字符,比如"《》" 、"<>"等,如果包含这些字符,需要在变量中添加“?html”。 同样,文件名称中包含特殊字符的话,也会造成导出的word打不开,需要这样写, fileName!2.word"""<>"?htmlword{fileName?html},也可能文件名称也为空,这时候需要这样写${(fileName?html)!}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
生成Word文件可以使用Apache POI库来操作,而使用Freemarker可以方便地生成Word模板。以下是Java通过Freemarker生成Word文件的代码实现: 1. 首先,需要引入Apache POI和Freemarker的相关依赖包。 2. 创建Freemarker配置对象,并设置模板文件路径和编码方式: ``` Configuration configuration = new Configuration(Configuration.VERSION_2_3_30); configuration.setDefaultEncoding("UTF-8"); configuration.setClassicCompatible(true); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setDirectoryForTemplateLoading(new File("templates")); ``` 其中,templates为存放模板文件的目录。 3. 加载模板文件,并生成数据模型: ``` Template template = configuration.getTemplate("template.ftl"); Map<String, Object> dataModel = new HashMap<>(); dataModel.put("title", "生成Word文件示例"); dataModel.put("content", "这是一份生成Word文件的示例文件。"); ``` 其中,template.ftl为模板文件名称,可以根据实际情况进行修改。dataModel是一个Map类型的数据结构,用于保存模板中需要替换的数据。 4. 创建Word文档对象,并读取模板内容: ``` XWPFDocument document = new XWPFDocument(); StringWriter writer = new StringWriter(); template.process(dataModel, writer); String content = writer.toString(); ``` 其中,XWPFDocument是Apache POI库中用于操作Word文档的类。 5. 将模板内容写入Word文档: ``` XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(content); ``` 6. 保存Word文档: ``` FileOutputStream out = new FileOutputStream("output.docx"); document.write(out); out.close(); document.close(); ``` 其中,output.docx为生成Word文件名称,可以根据实际情况进行修改。 完整代码示例: ``` import java.io.*; import java.util.*; import org.apache.poi.xwpf.usermodel.*; import freemarker.template.*; public class WordGenerator { public static void main(String[] args) throws Exception { Configuration configuration = new Configuration(Configuration.VERSION_2_3_30); configuration.setDefaultEncoding("UTF-8"); configuration.setClassicCompatible(true); configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); configuration.setDirectoryForTemplateLoading(new File("templates")); Template template = configuration.getTemplate("template.ftl"); Map<String, Object> dataModel = new HashMap<>(); dataModel.put("title", "生成Word文件示例"); dataModel.put("content", "这是一份生成Word文件的示例文件。"); XWPFDocument document = new XWPFDocument(); StringWriter writer = new StringWriter(); template.process(dataModel, writer); String content = writer.toString(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(content); FileOutputStream out = new FileOutputStream("output.docx"); document.write(out); out.close(); document.close(); } } ``` 其中,template.ftl文件内容如下: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>${title}</title> </head> <body> <h1>${title}</h1> <p>${content}</p> </body> </html> ``` 以上代码实现了通过Freemarker生成Word文件的功能,可以根据实际情况进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值