word文档的导出(用freemarker模板导出)(桃)
1、将要导出的word文档另存为xml格式的
2、用文档编辑器打开(如:notepad++),将要展示的数据用${name}的形式替换,“name”对应数据库中的字段
3、根据模板生成
package com.idcsol.apps.common.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class DocumentHandler {
private Configuration configuration = null;
public DocumentHandler() {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
}
public void createDoc(Map<String,Object> dataMap,String fileName,
String tempName) throws UnsupportedEncodingException {
//dataMap 要填入模本的数据文件
//设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
//这里我们的模板是放在template包下面
configuration.setClassForTemplateLoading(this.getClass(), "/com/idcsol/apps/controller/positionSet/template");
Template t=null;
try {
//test.ftl为要装载的模板
t = configuration.getTemplate(tempName);
} catch (IOException e) {
e.printStackTrace();
}
//输出文档路径及名称
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("---------------------------");
}
}
4、控制器中使用
DocumentHandler mdoc = new DocumentHandler ();
String resourcepath = "文件名.doc";
mdoc.createDoc(dataMap, resourcepath,"remoceApplyOut.ftl");
5、通过上述实现,word文档已经导出到服务器上,但是,一般会需要把文件下载到客户机上
实现代码:
package com.idcsol.apps.common.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;
import com.idcsol.base.common.constant.BaseConst;
import com.idcsol.base.common.utils.StringUtil;
public class UploadUtil {
private static Log log = LogFactory.getLog(UploadUtil.class);
/**
* 上传文件(下载文件的话不需要该方法)
* @param file
* @return 文件在服务器的相对路径
*/
public static String uploadFile(MultipartFile file) {
String url = "";
String path = "/upload";
try {
// 获取绝对路径
String realPath = com.idcsol.apps.common.constant.Const.REAL_PATH + path;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
String date = df.format(new Date());
realPath = realPath + "/" + date;
// 创建文件夹
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 构建文件名
String fileName = "" + new Date().getTime();
int ext = 0;
if ((ext = file.getOriginalFilename().lastIndexOf(".")) != -1) {
// 扩展名
fileName += file.getOriginalFilename().substring(ext);
}
path = path + "/" + date + "/" + fileName; // 相对路径
url = realPath + "/" + fileName;
file.transferTo(new File(url));
} catch (Exception e) {
log.error(StringUtil.getExceptionDetail(e));
return "";
}
return path;
}
public static void downloadFile(String resourcepath,String filename, HttpServletRequest request,
HttpServletResponse response) {
// String[] fileName1=resourcepath.split("/");
// String fileName=fileName1[fileName1.length-1];
FileInputStream fis = null;
OutputStream out = null;
if(StringUtil.isNotEmpty(filename) && StringUtil.isNotEmpty(resourcepath)) {
try {
//fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF");
realPath=realPath.replace("\\hrm\\WEB-INF","");
realPath.trim();
fis = new FileInputStream(new File(resourcepath));
//设置响应头和保存文件名
response.setContentType("application/x-download");
response.addHeader("Content-Disposition","attachment;filename=" + filename);
//写出流信息
int b = BaseConst.ZERO;
out = response.getOutputStream();
byte [] buf = new byte[1024];
while(-1 != (b = fis.read(buf))) {
out.write(buf,0,b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
6、控制器中调用下载的方法
UploadUtil.downloadFile(resourcepath, Docname, request, response);//文件路径、文件名
7、如果导出的文件在服务器上没有必要留下来的话,可以将对应文件删除
public boolean delDoc(HttpServletRequest request ,HttpSession httpSession,
String docName) throws UnsupportedEncodingException {
Result<Object> result = new Result<Object>();
String docname=docName;
// System.out.println(docname+"docname");
String lj= request.getRealPath("/")+docname;
boolean flag = false;
File file = new File(lj);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
/* if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(lj);
}*/ /*else { // 为目录时调用删除目录方法
return deleteDirectory(lj);
} */
deleteFile(lj);
}
return flag;
}
private boolean deleteFile(String lj) {
// TODO Auto-generated method stub
boolean flag = false;
File file = new File(lj);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
// System.out.println("删除成功");
flag = true;
}
return flag;
}
8、控制器中调用删除文件的方法
delDoc(request,httpSession,Docname);
需要导入freemarker的jar包
maven pom.xml的写法
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.8</version>
</dependency>
(导出word文档的方法完)
word文档的导出(用freemarker模板导出)(桃)的更多相关文章
- JAVAWEB导出word文档,遍历表格数据,导出图片
这是写的另一个导出word方法:https://www.cnblogs.com/pxblog/p/12790904.html 本次使用的是easypoi框架 官方教程:https://opensour ...
- word 文档导出 (freemaker+jacob)--java开发
工作中终于遇到了 需要导出word文旦的需求了.由于以前没有操作过,所以就先百度下了,基本上是:博客园,简书,CDSN,这几大机构的相关帖子比较多,然后花了2周时间 才初步弄懂. 学习顺序: 第一阶 ...
- 将HTML导出生成word文档
前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...
- java使用freemarker生成word文档
1.原料 开源jar包freemarker.eclipse.一份模板word文档 2.首先设计模板word文档 一般,通过程序输出的word文档的格式是固定的,例如建立一个表格,将表格的标题写好,表格 ...
- 关于PowerDesigner导出数据库表到word文档
关于PowerDesigner导出数据库表到word文档 一.查看全部模板: powerdesigner默觉得我们提供了非常多的模版,在工具栏中选择[Report(报告)--->Report T ...
- MindManager导出Word文档功能介绍
Mindmanager思维导图软件作为一款能与Microsoft office软件无缝集成的思维导图软件,支持Word文档的快速导入与导出,并支持Word文档的目录生成.模板套用等,极大地方便了用户完 ...
- 数据库数据怎样导出成Excle表格或Word文档?
数据导出:将数据库的数据导出成Excel工作表或Word文档 方法:将一个泛型集合导出出去 主要使用: SaveFileDialog StreamWriter 导出代码: private void b ...
- SpringBoot+FreeMarker开发word文档下载,预览
背景: 开发一个根据模版,自动填充用户数据并下载word文档的功能 使用freemarker进行定义模版,然后把数据进行填充. maven依赖: <parent> <groupId& ...
- Struts2利用iText导出word文档(包含表格)以提供下载
J2EE ExcelStrutsXML 在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以word文档形式下载课表.将课表导出到excel里的功能他们已经实现了, ...
- JAVA Asponse.Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件
一,由于该 jar 包不是免费的, maven 仓库一般不会有,需要我们去官网下载并安装到本地 maven 仓库 1,用地址 https://www-evget-com/product/564 ...
随机推荐
- UITableView上添加按钮,按钮点击效果延迟的解决办法
在自定义的TableView的初始化方法做如下操作 - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame: ...
- vue使用原生js实现滚动页面跟踪导航高亮
需要使用vue做一个专题页面. 滚动页面指定区域导航高亮. BetterScroll:可能是目前最好用的移动端滚动插件 如何自定义CSS滚动条的样式? 监听滚动页面事件,对比当前页面的位置与元素的位置 ...
- Linux 安装Nginx+PHP+MySQL教程
一.安装nginx 通过yum安装openssl: yum -y install openssl openssl-devel 通过yum安装pcre: yum -y install pcre-deve ...
- nrf528xx bootloader 模块介绍(转载)
转载https://www.cnblogs.com/rfnets/p/8205521.html 1. bootloader 的基本功能: 启动应用 几个应用之间切换 初始化外设 nordic nrf5 ...
- Linux操作系统启动流程
一般来说,所有的操作系统的启动流程基本就是: 总的来说,linux系统启动流程可以简单总结为以下几步:1)开机BIOS自检,加载硬盘.2)读取MBR,进行MBR引导.3)grub引导菜单(Boot L ...
- Cinder配置多Ceph后端步骤
1. 检查cinder当前backend配置 使用cinder service-list,查看cinder-volume服务的Host字段格式. 旧版格式: 新版格式: 旧版中Host字段是cinde ...
- visual studio 2019安装秘钥
美国时间4.2微软发布了最新版本的visual studio 2019 现在贴出visual studio2019的秘钥,有需要的请自取: Visual Studio 2019 Enterprise( ...
- Windows清理打印池的方法
另存为bat运行 @echo off title 快速清除打印队列 echo. echo 停止打印机服务 net stop spooler>nul echo. del /q /f %wind ...
- dedecms 标签
article文章页标签 文档工具:http://tools.dedecms.com/dedetag_maker/article.html {dede:field.title/} 文章标题 {dede ...
- debug环境下打印
#ifdef DEBUG # define NSLog(...) NSLog(__VA_ARGS__) #else # define NSLog(...) {} #endif