java 使用freemarker导出word

freemarker-2.3.8.jar

@EnableAutoConfiguration(exclude = { FreeMarkerAutoConfiguration.class })
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

导出工具类

import java.net.URLEncoder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * 导出word工具类
 */
public class ExportWord {

    private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
    private Configuration configuration;
    private String encoding;
    private String exportPath = "D:\\test\\";

    /**
     * 构造函数
     * 配置模板路径
     * @param encoding    
     */
    public ExportWord(String encoding) {
        this.encoding = encoding;
        configuration = new Configuration();
        configuration.setDefaultEncoding(encoding);
        configuration.setClassForTemplateLoading(this.getClass(), "/word");
    }

    /**
     * 获取模板
     * @param name
     * @return
     * @throws Exception    
     */
    public Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }

    /**
     * 导出word文档到指定目录
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception    
     */
    public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
        logger.debug("导出word到D:\test");
        //如果目录不存在,则创建目录
        File exportDirs = new File(exportPath);
        if (!exportDirs.exists()) {
            exportDirs.mkdirs();
        }
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
        getTemplate(tplName).process(data, writer);
    }

    /**
     * 导出word文档到客户端
     * @param response
     * @param fileName
     * @param tplName
     * @param data
     * @throws Exception    
     */
    public void exportDoc(HttpServletResponse response, String fileName, String tplName, Map<String, Object> data) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/msword");
        response.setHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" +  URLEncoder.encode(fileName , "UTF-8"));
        // 把本地文件发送给客户端
        Writer out = response.getWriter();
        Template template = getTemplate(tplName);
        template.process(data, out);
        out.close();
    }
}

controller

/**
	 * word导出
	 */
	@PostMapping("/exportLogWord")
	// @Authorization
	@ApiImplicitParams({
			@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"), })
	public void exportLogWord(@RequestBody Map<String, String> params, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if(StringUtils.isNotBlank(params.get("id"))){
			supervisorService.exportLogWord(params.get("id"), response);
		}
	}

service

/**
     * 监理日志导出word
     */
	@Override
	public void exportLogWord(String id ,HttpServletResponse response) {
        String fileName = "监理日志"+DateUtils.formatDate(new Date(), "yyyyMMddHHmmss")+".doc"; //文件名称
        Map<String,Object> dataMap = new HashMap<>();
        SupervisorLog supervisorLog = supervisorLogRepository.findById(id);
        Date recordDate = supervisorLog.getRecordDate();
        dataMap.put("logCode", supervisorLog.getLogCode());
        dataMap.put("year", (new SimpleDateFormat("yyyy")).format(recordDate));
        dataMap.put("month", (new SimpleDateFormat("MM")).format(recordDate));
        dataMap.put("day", (new SimpleDateFormat("dd")).format(recordDate));
        dataMap.put("week", supervisorLog.getWeek());
        dataMap.put("dayWeather", supervisorLog.getDayWeather());
        dataMap.put("nightWeather", supervisorLog.getNightWeather());
        dataMap.put("maxTemperature", supervisorLog.getMaxTemperature());
        dataMap.put("minTemperature", supervisorLog.getMinTemperature());
        dataMap.put("workContent", supervisorLog.getWorkContent());
        try {
			new ExportWord("UTF-8").exportDoc(response, fileName, "supervisorLog.ftl", dataMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}	

word到ftl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值