基于Java模板技术动态生成Word文档

一.使用word文档编辑好模版,如下图:

基于Java模板技术动态生成Word文档_第1张图片

基于Java模板技术动态生成Word文档_第2张图片

编辑好模板之后选择另存为,保存为xml格式。

二.编写java代码

采用的是FreeMarker模板引擎。需要下载对应的jar包,如果用的是Maven,只需在pom.xml中加入以下代码即可。


    
	  org.freemarker
	  freemarker
	  2.3.25-incubating
	 

Service:

package Solin.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import Solin.domain.Student;
import Solin.mapper.DynamicallyGeneratedWordMapper;
import freemarker.cache.URLTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

@Service
public class DynamicallyGeneratedWordService {
	private static Configuration freemarkerConfig;
	
	static {
		freemarkerConfig = new Configuration(Configuration.VERSION_2_3_22);
		freemarkerConfig.setEncoding(Locale.getDefault(), "UTF-8");
	}
	
	@Autowired
	private DynamicallyGeneratedWordMapper dynamicallyGeneratedWordMapper;
	
	/**
	 * 生成word文档
	 * @param filePath
	 * @throws TemplateNotFoundException
	 * @throws MalformedTemplateNameException
	 * @throws ParseException
	 * @throws IOException
	 * @throws TemplateException
	 */
	public void genWordFile(String filePath) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException{
		List stuList = dynamicallyGeneratedWordMapper.getStudentList();
		Map result = new HashMap();
		result.put("date", new Date());
		result.put("teacher", "Solin");
		result.put("topic", "基于Java模板技术动态生成Word文档");
		result.put("count", stuList.size());
		result.put("maleCount", dynamicallyGeneratedWordMapper.getManNumber());
		result.put("femaleCount", dynamicallyGeneratedWordMapper.getFemaleNumber());
		result.put("stuList", stuList);
		
		freemarkerConfig.setTemplateLoader(new URLTemplateLoader() {
			
			@Override
			protected URL getURL(String arg0) {
				return DynamicallyGeneratedWordService.class.getResource("/test.xml");//此处需要注意test.xml模板的路径,不要搞错了,否则获取不到模板,我是放在src/main/java目录下
			}
		});
		
		Template temp = freemarkerConfig.getTemplate("test.xml");
		
		File targetFile = new File(filePath);
		Writer out = new OutputStreamWriter(new FileOutputStream(targetFile),"UTF-8");
		
		//执行模板替换
		temp.process(result, out);
		out.flush();
	}
}

我的test.xml文件的位置:


Student实体类:

package Solin.domain;

/**
 * @author Solin
 * 学生信息实体类
 *
 */
public class Student {
	private Integer id;//主键
	private String name;//姓名
	private String sex;//性别
	private String age;//年龄
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}
Controller:

package Solin.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import Solin.domain.Student;
import Solin.service.DynamicallyGeneratedWordService;
import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * @author Solin
 * 基于Java模板技术动态生成Word文档 
 */
@Controller
public class DynamicallyGeneratedWordController {
	@Autowired
	private DynamicallyGeneratedWordService dynamicallyGeneratedWordService;
	
	@ResponseBody
	@RequestMapping("/getStudentList")
	public String getStudentList(){
		String result = "成功";
		try {
			dynamicallyGeneratedWordService.genWordFile("d://stu.doc");
		} catch (TemplateNotFoundException e) {
			result = "失败";
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			result = "失败";
			e.printStackTrace();
		} catch (ParseException e) {
			result = "失败";
			e.printStackTrace();
		} catch (IOException e) {
			result = "失败";
			e.printStackTrace();
		} catch (TemplateException e) {
			result = "失败";
			e.printStackTrace();
		}
		return result;
	}
}

XML模版中需要做以下修改:


表格数据是多行的,所以要循环。

基于Java模板技术动态生成Word文档_第3张图片

我们在xml模版中做以下修改:找到上图中红色框框所在的地方,然后按下图修改

基于Java模板技术动态生成Word文档_第4张图片

里面的内容依次改为对应的:${stu.id} ${stu.name} ${stu.sex} ${stu.age}这里的id name sex age是和Student实体类对应的。


 三.到此基本完成了动态模版的生成,测试结果图下图:

基于Java模板技术动态生成Word文档_第5张图片


基于Java模板技术动态生成Word文档_第6张图片





你可能感兴趣的:(Java小demo)