直接上代码:
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. ZFNet: Visualizing and Understanding Convolutional Networks

    目录 论文结构 反卷积 ZFnet的创新点主要是在信号的"恢复"上面,什么样的输入会导致类似的输出,通过这个我们可以了解神经元对输入的敏感程度,比如这个神经元对图片的某一个位置很敏 ...

  2. DP转LVDS方案 瑞奇达CS5211替代PS8625方案 CS5211芯片

    PS8625将作为DP或eDP接收器设备出现在视频源中,并将作为LVDS显示面板的LVDS源设备.该设备是一个完全集成的解决方案,不需要外部CPU.内存.时钟基准或电压调节器.PS8625可配置为从显 ...

  3. Java+Eclipse+MySQL+Swing实现学生会考成绩管理系统(免费完整项目)

    版权声明:原创不易,本文禁止抄袭.转载,侵权必究! 目录 一.需求开发文档 二.数据库设计文档 三.功能模块部分代码及效果展示 四.完整源码下载 五.作者Info 一.需求开发文档 项目完整文件列表: ...

  4. mysql 语句中 sum函数求和 null 变 0

    https://blog.csdn.net/Z_passionate/article/details/83821039

  5. PHP DateTime类常用方法总结

    实例化: $date = new DateTime(); $date = new DateTime('2018-01-01'); $date = new DateTime('tomorrow'); $ ...

  6. 乌龟NOI

    题目描述 一只乌龟由于智商低下,它只会向左或向右走,不过它会遵循主人小h的指令:F(向前走一步),T(掉头). 现在小h给出一串指令,由于小h有高超的计算能力,他可以马上知道乌龟最后走到哪里.为了难倒 ...

  7. Pytest_参数化(10)

    pytest参数化有两种方式: mark的parametrize标记:@pytest.mark.parametrize(变量名,变量值),其中变量值类型为列表.元组或其它可迭代对象. fixture的 ...

  8. 您应该知道的35个绝对重要的Linux命令

    https://mp.weixin.qq.com/s?__biz=MzU3NTgyODQ1Nw==&mid=2247499293&idx=2&sn=1353b78d6ad01d ...

  9. yum是什么?repo文件详解,epel简介,yum源的更换,repo和epel区别

    yum是什么?repo文件详解,epel简介,yum源的更换,repo和epel区别 简单概括: repo和epel的关系 repo是配置源的,即配置从哪里下载包(以及依赖关系)的. epel是作为桥 ...

  10. dispatcher-servlet.xml文件配置模板

    完整代码如下: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http:/ ...