获取数据的过程因程序不同而有异;我就不再赘述了。
对获取的数据进行循环处理生成需要的word临时文件
List<String> filePathList=new ArrayList<>();
// String exportFilePaths = null;
for (int i = 0 ; i < transferOrders.size() ; i++){
BasSystemDoc systemDocTemp = new BasSystemDoc();
BeanUtils.copyProperties(systemDoc,systemDocTemp);
CrewTransferOrder crewTransferOrder = transferOrders.get(i);
Map<String, Object> fillMap = dataTransFormation(crewTransferOrder,(Date) map.get("date"));
template.render(fillMap);
String exportFilePath = YuYouConfig.getUploadPath() + System.currentTimeMillis() +
crewTransferOrder.getCName() + DocxConstant.SUFFIX_DOCX;
// template.writeToFile(exportFilePath);
template.write(new FileOutputStream(exportFilePath));
filePathList.add(exportFilePath);
//保存为体系文件
systemDocTemp.setFilePath(exportFilePath);
systemDocService.saveDoc(systemDocTemp);
}
template.close();
String zipFilePath=genZipFile(filePathList);
this.genFileStream(zipFilePath,response,template);
注:template是XWPFTemplate类,可以在controller中当作一个参数返回过来
template.write()这里只能用write方法往本地写进文件,而不能使用template.writeToFile()方法,因为writeToFile方法内有finsh()会把template模板关掉,由于需要生成多个word所以在for循环结束之前不能关掉它!最后完成文件保存到本地。
Map<String, Object> fillMap = dataTransFormation(crewTransferOrder,(Date) map.get("date"));
该语句就是生成template模板需要的数据结构;
介绍一下代码中提及到的方法类:
genZipFile方法:
public String genZipFile(List<String> filePathList) throws IOException {
List<File> filesToCompress = new ArrayList<>(); // 要压缩的文件列表
for (int i = 0 ; i < filePathList.size() ; i++){
File file = new File(filePathList.get(i));
filesToCompress.add(file);
}
String zipFilePath = "compressed_files.zip";// 生成的ZIP文件名
compressFiles(filesToCompress, zipFilePath);
return zipFilePath;
}
compressFiles方法:
private static void compressFiles(List<File> filesToCompress, String zipFileName) throws IOException {
try (FileOutputStream fos = new FileOutputStream(zipFileName)) {
try (BufferedOutputStream bos = new BufferedOutputStream(fos)) {
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
for (File file : filesToCompress) {
addFileToZip(zos, file, null);
}
}
}
}
}
addFileToZip方法:
private static void addFileToZip(ZipOutputStream zos, File file, String parentPath) throws IOException {
if (!file.exists()){ return ;};
byte[] buffer = new byte[4096];
int bytesRead;
if (parentPath == null || parentPath.isEmpty()) {
parentPath = "";
} else {
parentPath += "/";
}
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null && children.length > 0) {
for (File child : children) {
addFileToZip(zos, child, parentPath + file.getName());
}
}
} else {
try (InputStream is = new FileInputStream(file)) {
zos.putNextEntry(new ZipEntry(parentPath + file.getName()));
while ((bytesRead = is.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
zos.closeEntry();
}
}
}
genFileStream方法:
简单介绍一个吧代码就不贴了
可以看得到这个方法是需要一个地址的通过response把文件转为流然后返回给前端。
到此就就是一个完整的从生成word到打包压缩并返回给前端一套功能就结束了。
最后结果如下: