直接上代码:
Map<String, Object> dataMap = afterLoanReportService.exportReport(startDate, endDate);
//new FtlToWordUtil().downContract(request, response, dataMap, "ABS产品贷后分析报告.doc", "ABS产品贷后分析报告.ftl");
String fileName = "ABS产品贷后分析报告.docx";
//电脑桌面路径
//String desktopUrl = FileSystemView.getFileSystemView().getHomeDirectory().getPath();
//xmlTemp:填充完数据的临时xml
String xmlTemp = tempUrl + "\\" + fileName + ".xml";
File f = new File(xmlTemp);
Writer w = new FileWriter(f);

//1.把map中的数据动态由freemarker传给xml
XmlToExcel.process("ABS产品贷后分析报告.xml", dataMap, w);

//2.把填充完成的xml写入到docx中
XmlToDocx xtd = new XmlToDocx();

InputStream is = this.getClass().getResourceAsStream("/template/ABS产品贷后分析报告.docx");
xtd.outDocx(f, is, fileName, response, request);
return ResultModelUtil.getSucessData();

package com.tebon.ams.util;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class XmlToExcel {
private static XmlToExcel tplm = null;
private Configuration cfg = null;

@SuppressWarnings("deprecation")
private XmlToExcel() {
cfg = new Configuration();
try {
// 注册tmlplate的load路径
cfg.setClassForTemplateLoading(this.getClass(), "/template/");
} catch (Exception e) {

}
}

private static Template getTemplate(String name) throws IOException {
if (tplm == null) {
tplm = new XmlToExcel();
}
return tplm.cfg.getTemplate(name);
}

/**
*
* @param templatefile
* 模板文件
* @param param
* 需要填充的内容
* @param out
* 填充完成输出的文件
* @throws IOException
* @throws TemplateException
*/
@SuppressWarnings("rawtypes")
public static void process(String templatefile, Map param, Writer out) throws IOException, TemplateException {
// 获取模板
Template template = XmlToExcel.getTemplate(templatefile);
template.setOutputEncoding("UTF-8");
// 合并数据
template.process(param, out);
if (out != null) {
out.close();
}
}
}

package com.tebon.ams.util;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

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

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class XmlToDocx {
/**
* @param documentFile 动态生成数据的docunment.xml文件
* @param ins docx的文件流
* @param fileName 导出文件名称
* @throws ZipException
* @throws IOException
*/
@SuppressWarnings("resource")
public void outDocx(File documentFile, InputStream ins, String fileName,
HttpServletResponse response, HttpServletRequest request) throws ZipException, IOException {
FtlToWordUtil.setDownloadHeader(request, response, fileName);
response.setContentType("application/force-download");// 设置强制下载不打开
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//指定下载的文件名
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

File docxFile = new File(fileName);
ZipOutputStream zipout = null;
InputStream in = null;
InputStream is = null;

try {
OutputStream os = new FileOutputStream(docxFile);
int bytesRead = 0;
byte[] buffer2 = new byte[8192];
while ((bytesRead = ins.read(buffer2, 0, 8192)) != -1) {
os.write(buffer2, 0, bytesRead);
}
os.close();
ins.close();
log.info("outDocx 文件大小docxFile.length():{}", docxFile.length());

ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
zipout = new ZipOutputStream(response.getOutputStream());
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
is = zipFile.getInputStream(next);
// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
in = new FileInputStream(documentFile);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
zipout.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (zipout != null) {
try {
zipout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (docxFile != null) {
try {
docxFile.delete();// 删除临时文件
} catch (Exception e) {
e.printStackTrace();
}
}
documentFile.delete();
}
}

public void downloadDocx(File documentFile, InputStream ins, String fileName, String jieShiShuDoc,
HttpServletResponse response, HttpServletRequest request) throws Exception {
if (ObjectUtil.isEmpty(jieShiShuDoc)) {
outDocx(documentFile, ins, fileName, response, request);
}
String tempFilePath = File.separator + "home" + File.separator + "temp" + File.separator + "ams-procedure" + File.separator + fileName;
String emptyFilePath = File.separator + "home" + File.separator + "temp" + File.separator + "ams-procedure" + File.separator + "empty.docx";
File emptyFile = new File(emptyFilePath);
this.downloadDocx(documentFile, ins, fileName, tempFilePath);
List<File> targetFile1 = new ArrayList<>();
targetFile1.add(new File(tempFilePath));
targetFile1.add(new File(jieShiShuDoc));
AppendDocx.appendDocx(emptyFile, targetFile1);
log.info("导出开始-downloadDocx-文件名fileName:" + fileName);
if (FileUtils.exportFile(fileName, emptyFilePath, response)) {
log.info("导出完成-downloadDocx-文件名fileName:" + fileName);
// 删除当前路径下文件
FileUtils.rm(tempFilePath);
FileUtils.rm(emptyFilePath);
log.info("删除本地文件成功,srcPath:" + tempFilePath);
}

}

@SuppressWarnings("resource")
public void downloadDocx(File documentFile, InputStream ins, String fileName, String tempFilePath) throws ZipException, IOException {
//FtlToWordUtil.setDownloadHeader(request, response, fileName);
/*response.setContentType("application/force-download");// 设置强制下载不打开
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//指定下载的文件名
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
*/
File docxFile = new File(fileName);
ZipOutputStream zipout = null;
InputStream in = null;
InputStream is = null;

FileOutputStream fos = null;
BufferedOutputStream bos = null;
fos = new FileOutputStream(tempFilePath);
bos = new BufferedOutputStream(fos);

try {
OutputStream os = new FileOutputStream(docxFile);
int bytesRead = 0;
byte[] buffer2 = new byte[8192];
while ((bytesRead = ins.read(buffer2, 0, 8192)) != -1) {
os.write(buffer2, 0, bytesRead);
}
os.close();
ins.close();
log.info("outDocx 文件大小docxFile.length():{}", docxFile.length());

ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
zipout = new ZipOutputStream(bos);
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
is = zipFile.getInputStream(next);
// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
in = new FileInputStream(documentFile);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
zipout.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (zipout != null) {
try {
zipout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (docxFile != null) {
try {
docxFile.delete();// 删除临时文件
} catch (Exception e) {
e.printStackTrace();
}
}
documentFile.delete();
}
}
}

java实现以docx格式导出的更多相关文章

  1. java导出2007版word(docx格式)freemarker + xml 实现

    http://blog.csdn.net/yigehui12/article/details/52840121 Freemarker+xml生成docx 原理概述:word从2003版就支持xml格式 ...

  2. java实现excel的导入导出(poi详解)[转]

    java实现excel的导入导出(poi详解) 博客分类: java技术 excel导出poijava  经过两天的研究,现在对excel导出有点心得了.我们使用的excel导出的jar包是poi这个 ...

  3. Java使用POI实现数据导出excel报表

    Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...

  4. java实现文件批量导入导出实例(兼容xls,xlsx)

    1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...

  5. Java实现大批量数据导入导出(100W以上) -(二)导出

    使用POI或JXLS导出大数据量(百万级)Excel报表常常面临两个问题: 1. 服务器内存溢出: 2. 一次从数据库查询出这么大数据,查询缓慢. 当然也可以分页查询出数据,分别生成多个Excel打包 ...

  6. Java项目的导入和导出

    在很多情况下,需要将当前的 Java工程传递给其他人继续工作, 或协同工作,或者是从其他人那里接收到传递来的Java项目, 就需要掌握 Java项目的导入和导出. 以 Hello World 为例: ...

  7. java使用POI将数据导出放入Excel

    本文主要是将数据库取出的数据按照自定义的行列格式导出到excel中,POI则是实现我们需求所用到的技术. POI介绍 使用spring boot导入相关依赖 获取数据(自行处理) 完整代码实例:创建e ...

  8. java 中Excel的导入导出

    部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字  的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...

  9. java的excel表格的导出与下载

    今天做一个java对excel表格的导出和下载的时候,从网络上搜寻了下载的模板,代码如下: 控制层: @RequestMapping(value = "excelOut_identifier ...

随机推荐

  1. 你真的会用react hooks?看看eslint警告吧!(如何发请求、提升代码性能等问题)

    前言 看过几个react hooks 的项目,控制台上几百条警告,大多是语法不规范,react hooks 使用有风险,也有项目直接没开eslint.当然,这些项目肯定跑起来了,因为react自身或者 ...

  2. 低成本CH7511芯片方案|CH7511电路设计参考|CS5211替代CH7511

    CH7511是主要用于设计eDP转LVDS转换器,怎么样设计一款低成本低BOM简单的DP转LVDS的转接设置,目前有一款可以替代兼容CH7511的方案电路,并且其设计电路整体BOM成本较低,并且设计简 ...

  3. 编写Java程序,现要求使用 dom4j 解析 city.xml 文档,实现省份及对应城市的联动特效,效果如图所示

    查看本章节 查看作业目录 需求说明: 现要求使用 dom4j 解析 city.xml 文档,实现省份及对应城市的联动特效,效果如图所示 实现思路: 创建解析 XML 文档类 ParseXML 和窗体类 ...

  4. Oracle数据库安装Version12c

    1.安装规划 Oracle数据库版本: Linuxamd64_12102_database 12c Linux服务器系统: CentOS Linux release 7.5.1804 (Core) 6 ...

  5. Ranger-AdminServer安装(开启Kerberos)

    Ranger-AdminServer安装, 同时开启Kerberos安全模式, 基于ranger版本0.7.0. 安装规划 10.43.159.240 zdh-240 10.43.159.245 zd ...

  6. CF995E Number Clicker

    题目分析 首先,我们必须明白,操作都是互逆的,\(1,2\)之间是可以互相转化的,这是不需证明的,对于操作\(3\),实际上,是求当前数的逆元,我们知道,逆元就是求当前数在模另一个数下的倒数,那么,逆 ...

  7. nginx及依赖包安装分享 百度网盘(pcre+openssl+zlib)

    链接:https://pan.baidu.com/s/1gggq1p-uZSmAw49o5xfl4g 提取码:ypoj 复制这段内容后打开百度网盘手机App,操作更方便哦 1.安装pcre 解压:ta ...

  8. Python_魔法属性和方法

    魔法属性 __doc__:表示类或方法的描述信息 __moudle__:表示当前操作对象的模块,当前模块时,显示__main__ __class__:表示当前操作对象的类型 __name__:表示类或 ...

  9. Flask_上下文(六)

    Flask中有两种上下文,应用上下文(application context)和请求上下文(request context) 当客户端发来请求时,请求上下文就登场了.请求上下文里包含了请求的各种信息, ...

  10. 梯度下降法实现(Python语言描述)

    原文地址:传送门 import numpy as np import matplotlib.pyplot as plt %matplotlib inline plt.style.use(['ggplo ...