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 ...
最新文章
- 计算机视觉:Bag of words算法实现图像识别与搜索
- SAP 移动类型详解
- 自动运维_无Agent自动化运维平台spug
- Power BI 如何获取数据做可视化
- 点击按钮弹出iframe_WEB安全(四) :CSRF与点击劫持
- spring+quartz实现定时调度
- java数字时钟代码,[Java教程]Javascript 数字时钟
- NodeJS 正则路由匹配
- element-ui中dialog和el-image组件冲突问题
- Mac出现启动问题怎么办
- 中国联通沃支付echop支付插件
- 找不到org.springframework.cloud.util.PropertyUtils
- 计算机专业 一级结构工程师,2018年一级结构工程师《计算机应用基础》练习题(8).doc...
- xposed+justTrustMe在逍遥模拟器上的安装配置
- 专门查英语单词的软件_有什么软件可以查英语单词
- LaTeX里插入数学公式
- 感受晋味新年俗 你的高铁票可享景区门票优惠
- Nginx禁止使用IP访问
- Python基础06-数据结构
- JDK下载和配置以及java的第一个程序:“Hello Java”
热门文章
- Android接入微信SDK之一:发起微信授权登录
- JavaScript -- 时光流逝(一):数据类型,变量,类型转换,函数
- 如何提高情商?我推荐你看这本《经理人参阅:情商与社交》
- erlang c erl_interface
- 驱动中如何访问CPU中的寄存器?
- 最新高通芯片型号大全,高通技术资料下载
- android和MTKP60哪个好,高通450和联发科p60哪个比较好?
- jquery uploadify在谷歌浏和火狐下无法上传的解决方案
- 神奇代码岛box.fun(https://box3.codemao.cn/?from=cmsqfilter=common)
- HTML5实例练习——《排班查询》