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();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM