通过FreeMarker生成word文档

1.先引入freemarker的jar包

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.13</version>
</dependency>

2.制作模板文件:

新建一个word文件:

将变量替换成${xxx},将文件另存为xml,编辑器打开xml文件,确保${xxx}内容正确。将文件已utf-8编码保存,另存为为.ftl

3.工具类WordUtils

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.ekingwin.bas.common.model.LeaveDto;
import com.ekingwin.bas.reportform.service.SbwxFybxReportService;
import com.sun.org.apache.bcel.internal.generic.NEW;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import sun.misc.BASE64Encoder;

@Service
public class WordUtilService {
	
	private Configuration configuration = null;
	//private final String WORD_URL = "TestWordDownload.ftl";
	
	public WordUtilService() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
	}
	
	/**
	 * 导出word 并提供下载
	 * @param response
	 * @param invarTitle 文档名称
	 * @param dataMap 文档数据
	 * @param docModel 文档模板
	 */
	public void download(HttpServletResponse response,String invarTitle,
			Map<String,Object> dataMap,String docModel) {
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			String fileName = invarTitle + "_"+System.currentTimeMillis() + ".doc";
			File file = createDoc(fileName,dataMap,docModel);
			
			response.setContentType("application/msword;charset=utf-8");
			response.addHeader("Content-Disposition", "attachment; filename=\""
		            + new String(fileName.getBytes(),"iso-8859-1") + "\"");
			
			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();
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 *   将文本信息转为word输出
	 * @param fileName 文件名
	 * @param dataMap  填充数据
	 * @param docModel doc模板
	 * @throws Exception 
	 */
	public File createDoc(String fileName,Map<String,Object> dataMap,String docModel) {
		
		configuration.setClassForTemplateLoading(this.getClass(), ""); //模板文件所在路径
		Template t = null;
		
		File file = new File(fileName);
		try {
			
	        t = configuration.getTemplate(docModel); //获取模板文件
			t.setEncoding("utf-8");
			
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),"utf-8"));
			t.process(dataMap, out);  //将填充数据填入模板文件并输出到目标文件
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		
		return file;
	}
	
	
	
	
	/*//获得数据
	private void getData(Map<String,Object> dataMap) {
		//
		dataMap.put("theme", "主题是这个");
		dataMap.put("name", "张三先生");
		dataMap.put("content", "内容为空");
		获取图片
		String base64 = getBase64(dto.getPicture());
		dataMap.put("image", base64);
	}
	
	//获得图片的base64编码
	private String getBase64(String imgUrl) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		URL url = null;
		InputStream in = null;
		HttpURLConnection httpUrl = null;
		byte[] by = new byte[1024];
		
		try {
			url = new URL(imgUrl);
			httpUrl = (HttpURLConnection)url.openConnection();
			httpUrl.connect();
			in = httpUrl.getInputStream();
			int len = -1;
			while((len = in.read(by)) != -1) {
				data.write(by, 0, len);
			}
			
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data.toByteArray());
	}*/
	
}

4.调用

public void downloadDoc(HttpServletResponse response) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("theme", "主题是这个");
		dataMap.put("name", "张三先生");
		dataMap.put("content", "内容为空");
		wordUtilService.download(response,"索赔通知书",dataMap,"TestWordDownload.ftl");
	}

参考:
java后台利用模板生成Word文档提供前台下载
java 根据模板,导出word并提供下载
java导出word的5种方式
[转载]java调用PageOffice生成word

发布了64 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/s_156/article/details/103616407