java实现以docx格式导出
直接上代码:
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格式导出的更多相关文章
- java导出2007版word(docx格式)freemarker + xml 实现
http://blog.csdn.net/yigehui12/article/details/52840121 Freemarker+xml生成docx 原理概述:word从2003版就支持xml格式 ...
- java实现excel的导入导出(poi详解)[转]
java实现excel的导入导出(poi详解) 博客分类: java技术 excel导出poijava 经过两天的研究,现在对excel导出有点心得了.我们使用的excel导出的jar包是poi这个 ...
- Java使用POI实现数据导出excel报表
Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...
- java实现文件批量导入导出实例(兼容xls,xlsx)
1.介绍 java实现文件的导入导出数据库,目前在大部分系统中是比较常见的功能了,今天写个小demo来理解其原理,没接触过的同学也可以看看参考下. 目前我所接触过的导入导出技术主要有POI和iRepo ...
- Java实现大批量数据导入导出(100W以上) -(二)导出
使用POI或JXLS导出大数据量(百万级)Excel报表常常面临两个问题: 1. 服务器内存溢出: 2. 一次从数据库查询出这么大数据,查询缓慢. 当然也可以分页查询出数据,分别生成多个Excel打包 ...
- Java项目的导入和导出
在很多情况下,需要将当前的 Java工程传递给其他人继续工作, 或协同工作,或者是从其他人那里接收到传递来的Java项目, 就需要掌握 Java项目的导入和导出. 以 Hello World 为例: ...
- java使用POI将数据导出放入Excel
本文主要是将数据库取出的数据按照自定义的行列格式导出到excel中,POI则是实现我们需求所用到的技术. POI介绍 使用spring boot导入相关依赖 获取数据(自行处理) 完整代码实例:创建e ...
- java 中Excel的导入导出
部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字 的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...
- java的excel表格的导出与下载
今天做一个java对excel表格的导出和下载的时候,从网络上搜寻了下载的模板,代码如下: 控制层: @RequestMapping(value = "excelOut_identifier ...
随机推荐
- Generating Adversarial Examples with Adversarial Networks
目录 概 主要内容 black-box 拓展 Xiao C, Li B, Zhu J, et al. Generating Adversarial Examples with Adversarial ...
- On the Optimization of Deep Networks: Implicit Acceleration by Overparameterization
目录 引 主要内容 定理1 Claim 1 Claim 2 定理2 证明 定理1的证明 Claim 1 的证明 Kronecker product (克罗内克积) Theorem 2 的证明 代码 A ...
- uniCloud爬虫获取网页数据
'use strict'; let request = require('request') let cheerio = require('cheerio'); //爬虫 let iconv = re ...
- Elasticsearch(二)--集群原理及优化
一.ES原理 1.索引结构ES是面向文档的 各种文本内容以文档的形式存储到ES中,文档可以是一封邮件.一条日志,或者一个网页的内容.一般使用 JSON 作为文档的序列化格式,文档可以有很多字段,在创建 ...
- <数据结构>图的最小生成树
目录 最小生成树问题 Prim算法:点贪心 基本思想:类Dijstra 伪代码 代码实现 复杂度分析:O(VlogV + E) kruskal算法:边贪心 基本思想: 充分利用MST性质 伪代码 代码 ...
- Java的发展简史
Java是由Sun Microsystems公司(简称Sun公司)于1995 年 5 月推出的 Java程序设计语言和Java平台的总称.Java语言是一种可以撰写跨平台应用软件的面向对象的程序设计语 ...
- 编写Java程序,实现控制台版的省市联动
返回本章节 返回作业目录 需求说明: 系统显示用户所有直辖市的名称,用户在控制台输入直辖市的名称,即可在控制台中显示该直辖市所管辖的所有区的名称. 实现思路: 创建省市联动类ProvincialLin ...
- Java常用的几种设计模式
本来想写点spring相关的东西的,想来想去,先写点设计模式的东西吧 什么是设计模式?套用百度百科的话解释吧 设计模式(Design Pattern)是一套被反复使用.多数人知晓的.经过分类的.代码设 ...
- Java中的对象、类、抽象类、接口的理解
1.对象 对象是个具体的东西,有着明确的属性特征和行为特征. 例如:你手上牵着的女朋友或男朋友就是个具体的对象. 如图中的苏格兰折耳猫,特征是耳朵向下呈折叠状,有着具体的颜色(你看到的颜色),并且和其 ...
- Oracle打怪升级之路二【视图、序列、游标、索引、存储过程、触发器】
前言 在之前 <Oracle打怪升级之路一>中我们主要介绍了Oracle的基础和Oracle常用查询及函数,这篇文章作为补充,主要介绍Oracle的对象,视图.序列.同义词.索引等,以及P ...