java 根据word模板导出导出word文档
一:新建需要导出word的模板,替换其中需要替换的字段,如下
二:在桌面另存为如下格式
三:另存的文件复制为如下路径,并修改文件后缀为ftl
四: java 代码如下
@RequestMapping(value = "/importTemplateRH", method = RequestMethod.POST)
public void generateWorkContactLetters(HttpServletResponse response,@RequestParam(value = "companyAndName") String companyAndName,@RequestParam(value = "work") String work) throws Exception {//获取当前的日期Date date = new Date();//设置要获取到什么样的时间SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//获取String类型的时间String createdate = sdf.format(date);/** 初始化配置文件 **/@SuppressWarnings("deprecation")Configuration configuration = new Configuration();configuration.setDefaultEncoding("utf-8");/** 加载模板 **///这个方法在eclipse跑和打jar包部署都可以获取到模版configuration.setClassForTemplateLoading(this.getClass(), "/templates");Template template = configuration.getTemplate("work.ftl");//这里是我获取的业务对象Map<String, Object> dataMap = new HashMap<>();dataMap.put("work", work);dataMap.put("companyAndName",companyAndName);dataMap.put("date", createdate == null ? "-" : com.sjft.common.core.utils.DateUtils.dateForOther(DateUtils.parseDate(createdate)));//开始word导出:导出我没有写死导出到什么磁盘,是通过浏览器输出随意存放修改。ServletOutputStream out = null;FileInputStream fin = null;String fileName = "报告.doc";try {//utils里创建word的方法:后面会给出代码File wordFile = WordUtil.createDoc(dataMap, template);fin = new FileInputStream(wordFile);response.setCharacterEncoding("utf-8");response.setContentType("application/msword;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");out = response.getOutputStream();byte[] buffer = new byte[1024];// 缓冲区int bytesToRead = -1;// 通过循环将读入的Word文件的内容输出到浏览器中while ((bytesToRead = fin.read(buffer)) != -1) {out.write(buffer, 0, bytesToRead);}} catch (Exception ex) {ex.printStackTrace();} finally {if (fin != null)fin.close();if (out != null)out.close();}
}
五:wordUtils代码如下
package com.sjft.patorl.propaganda.utils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
public class WordUtil {
//配置信息
public static Configuration configuration = null;
//这里注意的是利用WordUtils的类加载器动态获得模板文件的位置
private static String templateFolder;
//模板文件,可以方便修改
private static String fileInName;
public WordUtil() { }
public WordUtil(String fileInName){WordUtil.fileInName=fileInName;
// templateFolder = WordUtil.class.getClassLoader().getResource("…/…/")+“META-INF/libs”;
// templateFolder = templateFolder.replaceAll("%20", " ");
configuration = new Configuration();
configuration.setDefaultEncoding(“utf-8”);
try {
// configuration.setDirectoryForTemplateLoading(new File(templateFolder.substring(5)));
configuration.setClassForTemplateLoading(this.getClass(), “com/sjft/dailywork/resources/templates”);
configuration.getTemplate(fileInName);
configuration.setClassicCompatible(true); //解决null空值的问题
} catch (IOException e) {
e.printStackTrace();
}
}
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,String fileName) throws IOException { Template freemarkerTemplate = configuration.getTemplate(fileInName); File file = null; InputStream fin = null; ServletOutputStream out = null; try { // 调用工具类的createDoc方法生成Word文档 file = createDoc(map,freemarkerTemplate); fin = new FileInputStream(file); response.setContentType("application/msword"); // 设置浏览器以下载的方式处理该文件名 fileName += ".doc"; response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8")))); response.setCharacterEncoding("utf-8"); out = response.getOutputStream(); byte[] buffer = new byte[1024]; // 缓冲区 int bytesToRead = -1; // 通过循环将读入的Word文件的内容输出到浏览器中 while((bytesToRead = fin.read(buffer)) != -1) { out.write(buffer, 0, bytesToRead); }out.flush();} finally { if(fin != null) fin.close(); if(out != null) out.close(); if(file != null) file.delete(); // 删除临时文件 }
} public static File createDoc(Map<?, ?> dataMap, Template template) {String name = "test.doc"; File f = new File(name); Template t = template; try { // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开 Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8"); t.process(dataMap, w); w.close(); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } return f;
}
public static void main(String[] args) {String path = WordUtil.class.getClassLoader().getSystemResource("META-INF").getPath();System.out.println(path);
}
}
至此,java 导出word完成
java 根据word模板导出导出word文档相关推荐
- python excel word模板_Python将Excel数据插入Word模板生成详细内容文档
最近在实际工作中遇到的一个情况是,每个月固定时间要报送一批文档,文档的内容相似,有固定的模板,我这么懒的人肯定要想一个一劳永逸的办法.下面把搜索发现的情况记录一下,以备以后需要. Python有个叫做 ...
- Chimm.Excel —— 使用Java 操作 excel 模板文件生成 excel 文档
内容已不在此处更新,请移步https://blog.csdn.net/chimmhuang/article/details/111251115 1. 项目介绍 Chimm.Excel 是什么? 该程序 ...
- java word 模板_java通过word模板生成word文档
public static void main(String[] args) { //模板.文件.图片路径 String workPath=System.getProperty("user. ...
- java操作office和pdf文件java读取word,excel和pdf文档内容
在平常应用程序中,对office和pdf文档进行读取数据是比较常见的功能,尤其在很多web应用程序中.所以今天我们就简单来看一下Java对word.excel.pdf文件的读取.本篇博客只是讲解简单应 ...
- Java使用ftl模板文件生成Word,以及Word转换图片或Pdf工具类
Java使用ftl模板文件生成Word 一.写在前面 最近在项目中使用打印功能,发现这个功能我已经写过多次了,下面这个文章的发步日期在2020年,不得不感慨时间之快啊. https://blog.cs ...
- java word设置纸张a3,Word中进行设置A3文档纸张大小的操作技巧
在工作中最常用的纸质文档是A4的,但是我们有时候也需要用一些A3甚至其他纸张的文档,那么,在做文档的时候该如何设置呢?今天,学习啦小编就教大家在Word中进行设置A3文档纸张大小的操作技巧. Word ...
- SpringBoot+Poi-tl根据Word模板动态生成word(含动态行表格、合并单元格)
本编文章继SpringBoot+Poi-tl根据Word模板动态生成word(含动态行表格)文章之后 介绍Poi-tl导出word的延伸功能: 所需依赖以及word模板所属位置 见 SpringBoo ...
- 浅谈使用Word和Baklib制作帮助文档区别
几乎每个产品.应用都会设计常见问题界面.FAQ或帮助文档页面,这是一个产品必不可少的一部分,每个企业都会花上不少时间制作产品帮助文档,方便用户查阅产品使用问题.操作指南,快速上手使用产品,另一方面也是 ...
- 支持将数据导出到Excel文档的时候设置单元格格式的.NET控件Spire.DataExport
Spire.DataExport for .NET是e-iceblue公司推出的一款数据导出类.NET控件.作为一款专业的数据导出控件,Spire.DataExport for .NET可以帮助开发人 ...
- office文档管理服务器编辑,_卓正软件 - PageOffice官方网站 - 在线编辑Word、Excel的Office文档控件...
Office 组件 在线显示.编辑.保存Word文档 √ √ √ 在线显示.编辑.保存Excel文档 √ √ √ 在线显示.编辑.保存PowerPoint文档 √ √ √ 在线播放PowerPoint ...
最新文章
- 多线程读一个全局变量要不要加锁?还是说只是当修改全局变量的时候才要加锁?...
- 如何在Swift 3中创建调度队列
- java不同类之间参数传递_《java基础》整型包装类之间值得比较
- 论文笔记:ShuffleNet v1
- 写了 30 万行基础设施代码后,我们得出 5 个有用的经验
- oracle := 和=,oracle a:=100 和 b=:c 区别
- 计算机初级考试题库网络管理,计算机基础考试题库(含答案)
- oracle库锁表处理,oracle 数据库锁表处理 ORA-00031
- c语言程序设计19,C语言程序设计19.pdf
- c 语言 00字符串 截断,c语言截断字符串
- check GPU mem size on condor
- TG Pro for mac电脑温度管理工具
- caffe 绘制accuracy和loss曲线
- 信号检测与估计(1)
- 全国计算机一级考试试题题库---附答案
- leetcode简单之603.连续空余座位
- 机器学习学习过程记录
- 采购申请设置成抬头审批
- PHP CURL 账号密码 添加授权Authorization头Header
- linux GRO相关
热门文章
- 众昂矿业:萤石在光学领域的应用
- 关于北京大厦写字楼招商的网站制作
- 编程练习:定义一个表示时间的类Time
- 逍遥模拟器微信提示无法连接服务器,逍遥安卓模拟器显示网络异常,请查收最完整的解决方法...
- 2020-12-07(nnUNet_1)
- 机器学习基础——BP算法
- STM32入门学习 第四天
- 养老社区娱乐系统C语言,最新互站购买心愿社区智慧养老院信息化管理系统全开源版搬运...
- 在Python中使用Tensorflow进行神经风格迁移
- 模糊测试(fuzzing) 概念