栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot实现Freemarker生成word文档

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot实现Freemarker生成word文档

  • 导入Freemarker工具包

    org.springframework.boot
	spring-boot-starter-freemarker
  • 配置Freemarker工具类
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import javax.annotation.PostConstruct;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


@Component
public class FreeMarkerUtil {
	
	private Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
			
	
	@PostConstruct
	public void buildConfiguration() throws IOException {
		this.cfg.setDefaultEncoding("UTF-8");
		Resource path = new DefaultResourceLoader().getResource("classpath:/template");
		this.cfg.setDirectoryForTemplateLoading(path.getFile());
	}	

	
	private String renderTemplate(Template template, Object model) {
		StringWriter result = new StringWriter();
		try {
			template.process(model, result);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result.toString();
	}
	
	
	public void createFile(String ftlFileName,Object data,String filePath){
		Writer out=null;   
		try {
				String result = this.renderTemplate(cfg.getTemplate("/"+ftlFileName, "UTF-8"), data);
				File file = new File(filePath);
				if(file.exists()){
					FileUtils.deleteFile(filePath);
				}
				FileUtils.createFile(filePath);
				out = new BufferedWriter(new OutputStreamWriter(
						new FileOutputStream(filePath), "utf-8"), 1024);
				out.write(result);
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(out!=null){
					try {
						out.flush();
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
	   }
}
  • 编写下载工具类
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

public class DownloadUtils {
 
	public static void download(HttpServletRequest request, HttpServletResponse response,String filePath){
		File file =new File(filePath);
		response.reset();
		response.setContentType("application/msword; charset=utf-8");
        final String userAgent = request.getHeader("USER-AGENT");
        String finalFileName = null;
        try {
            if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
				finalFileName = new String(file.getName().getBytes(), "ISO8859-1");
            }else{
				finalFileName=URLEncoder.encode(file.getName(), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        response.setHeader("Content-Disposition", "attachment; filename="+finalFileName);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[1024];
	        int bytesRead;
	        try {
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				    bos.write(buff, 0, bytesRead);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}finally{
			try {
				if(bis!=null){
					bis.close();
				}
				if(bis!=null){
					bos.flush();
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  • 新建一个word文档,把需要用模板填充数据的地方暂时用数字代替

  •  把word文档另存为XML文件

  •  用XML文件格式化工具打开XML文件

  •  在项目resource文件夹中新建template文件夹,把xml文件后缀改为ftl文件放到template文件夹里面

  •  把ftl文件里的11、22等字符替换为你需要填充的字段,以下贴出核心代码段,Freemarker语法可以参考:Freemarker中文在线文档
<#if resultList??>
<#list resultList as record>















${record.name}

















${record.age}

















${record.className}

















${record.sno}





  • 编写Controller测试接口,模拟数据进行导出
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.frame.common.utils.DownloadUtils;
import com.frame.common.utils.FreeMarkerUtil;
import com.frame.system.entity.WordExportTest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@RestController
@RequestMapping("wordExport")
public class WordExportTestController {

	@Autowired
	private FreeMarkerUtil freeMarkerUtil;
	
	@GetMapping("exportWord")
	public void exportWord(HttpServletRequest req,HttpServletResponse res) {
		String filePath = req.getSession().getServletContext().getRealPath("/")+"exportWordTest.doc";
		Map map = Maps.newHashMap();
		List list = Lists.newArrayList();
		for(int i=0;i<10;i++) {
			WordExportTest t = new WordExportTest();
			t.setName("小米");
			t.setAge(20);
			t.setClassName("一班");
			t.setSno("1258DCc8552");
			list.add(t);
		}
		map.put("resultList", list);
		freeMarkerUtil.createFile("wordExportTest .ftl",map,filePath);
		DownloadUtils.download(req, res, filePath);
	}
}
  • 用Postman进行接口访问,然后保存即可

  •  导出后结果

  •  完成

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/346125.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号