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();
}
}
}
原文地址:https://www.cnblogs.com/muliu/p/12166868.html