freemarker根据word模板导出动态word(Excel模板导出Excel)

1.创建word模板
将需要替换的位置用"${}"代替,如下图:
在这里插入图片描述
2.将做好的模板文件保存为xml文件

3.打开xml文件,查看"${unitName}"是否在一起,不在一起的话删除多余部分

4.将修改的xml文件后缀改为ftl

5.工具类

package com.util;

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,String tempPath) throws UnsupportedEncodingException {
        //需要导出模板的包路径
    	try {
    		configuration.setDirectoryForTemplateLoading(new File(tempPath));
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
        //configuration.setClassForTemplateLoading(this.getClass(), "template");
        Object obj = this.getClass();
        Template t = null;
        try {
            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");
            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("文档导出完成");
    }
}

6.实例

	/**
	 * 导出word
	 */
	@RequiresPermissions("ai:park:houseContract:edit")
	@RequestMapping(value = "importWord")
	@ResponseBody
	public String importWord(HttpServletRequest request) {
		JSONArray jsonArray = new JSONArray();
    	JSONObject o = new JSONObject();
    	//获取跟路径
		String solutePath = request.getSession().getServletContext().getRealPath("/");
		String tempPath = solutePath+"/TemplateFile";
        Random myRandom = new Random();
        Date now = new Date();
        String strFileName = new SimpleDateFormat("yyyyMMddhhMMss").format(now) + myRandom.nextInt(10000) + "房屋租赁合同";
        String strSaveFileName = strFileName + ".doc";
        String strDirectoryName = "/TemplateFile/Files/" + new SimpleDateFormat("yyyyMM").format(now) + "/";
        String newFilePath = solutePath + strDirectoryName + strSaveFileName;
		DocumentHandler mdoc = new DocumentHandler();
		File file = new File(solutePath + strDirectoryName);
        if(!file.exists()){
            file.mkdir();
        }
        String id = request.getParameter("id");
        HouseContract houseContract = houseContractService.get(id);
        ImportBusiness importBusiness = importBusinessService.get(houseContract.getImportId());
        BusinessPark businessPark = businessParkService.get(importBusiness.getParkId());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("parkName", businessPark.getAName());
        map.put("businessName", importBusiness.getBusinessName());
        map.put("parkAddress", businessPark.getParkAddress());
        map.put("floor", houseContract.getFloor());
        map.put("qu", houseContract.getQu());
        map.put("unit", houseContract.getUnit());
        map.put("leaseTerm", houseContract.getLeaseTerm());
        String leaseStartDate = formatter.format(houseContract.getLeaseStartDate());
        map.put("leaseStartDate", leaseStartDate);
        String leaseEndDate = formatter.format(houseContract.getLeaseEndDate());
        map.put("leaseEndDate", leaseEndDate);
        map.put("monthlyRent", houseContract.getMonthlyRent());
        map.put("parkPost", businessPark.getParkPost());
        try {
			mdoc.createDoc(map, newFilePath,"房屋租赁合同.ftl",tempPath);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        o.put("success", true);
		o.put("filepath", newFilePath);
	    jsonArray.add(o);
		return jsonArray.toJSONString();
	}

导出文件下载参考Java获取文件路径后文件下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值