Java 导出word

** 需要jar包 freemarker-2.3.8.jar

1、创建word模板:

首先使用 offic或wps(我用的就是wps) 创建一个 word.docx 文件

在文件中输入  ${test} 并将文件保存为 xml 格式,其中 ${test} 就是我们在程序中要替换的目标,重点是 ${} 这个符号,里面的字内容可以自己定义。

Java 导出word

2、保存为 ftl 格式

将word.xml 直接重命名为 word.ftl,并放到项目目录下

Java 导出word

3、写代码:

package com.soft.out_word;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
 
@WebServlet("/OutWord")
public class OutWord extends HttpServlet {
       
	 private Configuration configuration = null;  
	private static final long serialVersionUID = -8933774728508351159L;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	    configuration = new Configuration();  
	    configuration.setDefaultEncoding("UTF-8");
	    Map<String,Object> dataMap=new HashMap<String,Object>();
	    dataMap.put("test", "测试");  
 
	    configuration.setClassForTemplateLoading(this.getClass(), "/");  //FTL文件所存在的位置  
	    Template template = null;  
	    try {  
	    	template = configuration.getTemplate("word.ftl"); //文件名  
	    	response.setHeader("Content-disposition","attachment;filename="+UUID.randomUUID().toString()+".doc");
	    	response.setContentType("application/msword;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			template.process(dataMap, writer);
			writer.close();
	    } catch (Exception e) {  
	    	e.printStackTrace();
	    }  
	}

}

从代码中可以看出,只需要将目标位置和需要加入的数据存在 dataMap 中即可,程序会将数据替换到目标位置。