FreeMaker实现word导出功能

Freemaker通过制定好的word模板,将数据绑定到变量中,然后转换成word,实现导出下载功能。

1、制作word模板

word
另存为xml格式的文件,然后将里面诸如allOrgs等变量,替换成${allOrgs}这种(如果表格中的内容需要对list变量进行循环,则加入<#list serviceBefFiveList as listKey>这种标签)。
在这里插入图片描述

2、后台代码

制作完模板,开始代码,首先maven依赖:

org.freemarker
freemarker
2.3.20

FreeMakerUtil实现模板读取,变量绑定,并将数据写入到bean中

package com.neusoft.freemaker.utils;

import java.io.StringWriter;
import java.util.Map;

import com.neusoft.freemaker.entity.ExportFileBean;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreeMarkerUtil {
		
	public static ExportFileBean createWordStream(Map<String, Object> dataMap,String templateName,String fileName){
		ExportFileBean bean =new ExportFileBean();
		try {
	           //创建配置实例 
	           Configuration configuration = new Configuration();
	           //设置编码
	            configuration.setDefaultEncoding("UTF-8");
	            //word模板位置
	            configuration.setClassForTemplateLoading(FreeMarkerUtil.class,"/com/neusoft/freemaker/template/");
	            //获取模板 
	            Template template = configuration.getTemplate(templateName);
	            StringWriter swriter = new StringWriter();
	            //生成 文件字符串
	            template.process(dataMap, swriter);
	    		bean.setFileName(fileName);
	    		
	    		bean.setIs(swriter.toString().getBytes("UTF-8"));;
	          
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return bean;
	    }


}

ExportFileBean

package com.neusoft.freemaker.entity;

public class ExportFileBean {

	private String fileName;
	private byte[] is;
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public byte[] getIs() {
		return is;
	}
	public void setIs(byte[] is) {
		this.is = is;
	}
	
}

功能下载类

package com.neusoft.freemaker.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.neusoft.core.web.BaseController;
import com.neusoft.freemaker.entity.ExportFileBean;
import com.neusoft.freemaker.utils.FreeMarkerUtil;

@Controller
@RequestMapping(value = "/freemaker")
public class FreemakerController extends BaseController {

	@RequestMapping(value = "/downFile")
	//@ResponseBody 这个不要,json返回格式才需要这个
	public void downFile(HttpServletResponse response) throws Exception {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		//获取测试map数据
		this.getReportMapData(dataMap);
		String templateName = "testModel.xml";
		String fileName = dataMap.get("titleName")+"质控报告("+ dataMap.get("reportDate")+").doc";
		ExportFileBean efb = FreeMarkerUtil.createWordStream(dataMap, templateName, fileName);
		
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型  
        response.setContentType("multipart/form-data");  

        //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫zms.jpg,这里是设置名称)  
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));  

        ServletOutputStream out=null;  


        try {
            //3.通过response获取ServletOutputStream对象(out)  
            out = response.getOutputStream();  

            out.write(efb.getIs());
            out.flush();
            out.close();

        } finally{
            try{
                 if(out!=null){
                    out.close();  
                    out.flush(); 
                 }
            }catch (IOException e) { 
                 e.printStackTrace();  
            }

        }
	
	public void getReportMapData(Map<String, Object> dataMap) throws Exception {
		dataMap.put("titleName", "XXX");
		dataMap.put("reportDate", "2019-12-01~2019-12-10");
		dataMap.put("districtName", "xxx市");
		dataMap.put("disLevel", "市属");
		dataMap.put("subLevel", "区县");
		dataMap.put("allOrgs", "58");
		dataMap.put("completeNums", "24");
		dataMap.put("incomNums", "34");
		dataMap.put("comRate", "41.38%");
		dataMap.put("cityOrgs", "26");
		dataMap.put("cityComOrgs", "14");
		dataMap.put("cityInComOrgs", "12");
		dataMap.put("cityComRate", "53.85%");
		dataMap.put("counOrgs", "32");
		dataMap.put("counComOrgs", "10");
		dataMap.put("counInComOrgs", "22");
		dataMap.put("counComRate", "31.25%");
		dataMap.put("phisOrgs", "288");
		dataMap.put("phisComOrgs", "0");
		dataMap.put("phisInComOrgs", "288");
		dataMap.put("phisComRate", "0%");
	}
}

3、前台js代码:

function dodownload(){
	window.location.href=basePath+"/freemaker/downFile";
}

点击按钮,进入dodownload()函数,然后就会像其他网站下载内容一下,在浏览器下侧出现下载的内容

4、注意事项:

String fileName = dataMap.get("titleName")+"质控报告("+ dataMap.get("reportDate")+").doc";

这里设置文件后缀时,一定不要设置成docx,否则下载下来的word打开会报错
在这里插入图片描述

可以使用 Apache POI 和 FreeMarker 来实现 Word 导出。具体步骤如下: 1. 引入依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` 2. 编写模板文件,例如 `template.ftl`: ```xml <?xml version="1.0" encoding="UTF-8"?> <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:body> <w:p> <w:r> <w:t>${title}</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>${content}</w:t> </w:r> </w:p> </w:body> </w:document> ``` 3. 编写 Java 代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import java.io.*; import java.util.HashMap; import java.util.Map; public class WordExportUtil { public static void export(Map<String, Object> dataMap, String templatePath, String outputPath) throws Exception { // 1. 创建 Configuration 对象 Configuration configuration = new Configuration(Configuration.VERSION_2_3_31); configuration.setDefaultEncoding("UTF-8"); // 2. 加载模板文件 Template template = configuration.getTemplate(templatePath); // 3. 创建 Word 文档对象 XWPFDocument document = new XWPFDocument(); // 4. 填充数据到 Word 文档中 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8"); template.process(dataMap, outputStreamWriter); outputStreamWriter.flush(); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText(line); } // 5. 输出 Word 文档 FileOutputStream fileOutputStream = new FileOutputStream(outputPath); document.write(fileOutputStream); fileOutputStream.close(); } } ``` 其中,`dataMap` 是模板中需要填充的数据,`templatePath` 是模板文件的路径,`outputPath` 是输出文件的路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值