java导出多个Word到指定路径,再生成压缩包从浏览器下载下来
思路:先逐个导出Word文件到服务器,再压缩,再返回给用户下载。
(导出Word用的是freemarker模板导出形式,这里不再赘述)
直接贴代码:
Controller文件:
@ApiOperation("同时导出多个Word文件")
@GetMapping("/exportZip")
public void exportZip(String instrumentIds, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> replaceMap = new HashMap<String, Object>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
if (!StringUtils.isEmpty(instrumentIds)) {
String[] split = instrumentIds.split(",");
List<String> files = new ArrayList<>();
for (int i = 0; i < split.length; i++) {
Instrument instrument = instrumentService.getById(split[i]);
if (instrument != null) {
replaceMap.put("instrument_name", instrument.getName());
DevicePlace devicePlace = devicePlaceService.getById(instrument.getPlaceId());
if (devicePlace != null) {
replaceMap.put("place_name", devicePlace.getName());
}
replaceMap.put("new_sn", instrument.getNewSn());
SysDepart sysDepart = sysDepartService.getById(instrument.getDeptId());
if (sysDepart != null) {
replaceMap.put("depart_name", sysDepart.getDepartName());
}
QueryWrapper<InstrumentUseRecord> instrumentUseRecordQueryWrapper = new QueryWrapper<>();
instrumentUseRecordQueryWrapper.eq("instrument_id", split[i]);
List<InstrumentUseRecord> instrumentUseRecordList = instrumentUseRecordService.list(instrumentUseRecordQueryWrapper);
List<Map<String, Object>> detailMapList = new ArrayList<>();
int order_number = 1;
for (InstrumentUseRecord instrumentUseRecord : instrumentUseRecordList) {
Map<String, Object> map = new HashMap<>();
map.put("order_number", order_number);
order_number++;
if (instrumentUseRecord.getUseTime() != null) {
map.put("use_time", simpleDateFormat.format(instrumentUseRecord.getUseTime()));
}
map.put("report_number", instrumentUseRecord.getReportNumber());
Integer checkBeforeUse = instrumentUseRecord.getCheckBeforeUse();
String checkBeforeUse_1 = "正 常( )";
String checkBeforeUse_2 = "不正常( )";
if (checkBeforeUse != null && checkBeforeUse == 0) {
checkBeforeUse_1 = "正 常( √ )";
} else if (checkBeforeUse != null && checkBeforeUse == 1) {
checkBeforeUse_2 = "不正常( √ )";
}
map.put("checkBeforeUse_1", checkBeforeUse_1);
map.put("checkBeforeUse_2", checkBeforeUse_2);
Integer checkInUse = instrumentUseRecord.getCheckInUse();
String checkInUse_1 = "正 常( )";
String checkInUse_2 = "不正常( )";
if (checkInUse != null && checkInUse == 0) {
checkInUse_1 = "正 常( √ )";
} else if (checkInUse != null && checkInUse == 1) {
checkInUse_2 = "不正常( √ )";
}
map.put("checkInUse_1", checkInUse_1);
map.put("checkInUse_2", checkInUse_2);
Integer checkAfterUse = instrumentUseRecord.getCheckAfterUse();
String checkAfterUse_1 = "正 常( )";
String checkAfterUse_2 = "不正常( )";
if (checkAfterUse != null && checkAfterUse == 0) {
checkAfterUse_1 = "正 常( √ )";
} else if (checkAfterUse != null && checkAfterUse == 1) {
checkAfterUse_2 = "不正常( √ )";
}
map.put("checkAfterUse_1", checkAfterUse_1);
map.put("checkAfterUse_2", checkAfterUse_2);
SysUser user = sysUserService.getById(instrumentUseRecord.getUserId());
if (user != null) {
map.put("user_name", user.getRealname());
}
map.put("remark", instrumentUseRecord.getRemark());
detailMapList.add(map);
}
replaceMap.put("detailMapList", detailMapList);
String fileName = WordUtil.exportDocByFreemarkerToServer("ZJ020.xml", instrument.getNewSn() + "仪器设备使用记录", replaceMap, response, request);
files.add(fileName);
}
}
WordUtil.writeZip(files, "仪器设备使用记录");
}
}
WordUtil文件:
public static String exportDocByFreemarkerToServer(String templateFileName, String docName, Map<String, Object> replaceMap, HttpServletResponse response, HttpServletRequest request) {
String fileName = "";
try {
Template template = configuration.getTemplate(templateFileName, "utf-8");
// 空值处理
for (String key : replaceMap.keySet()) {
Object value = replaceMap.get(key);
if (value == null) {
replaceMap.put(key, "");
}
}
String realPath = request.getSession().getServletContext().getRealPath("/");
String parentPath = new File(realPath).getParent() + "/table";
File dir = new File(parentPath);
if (!dir.exists()) {
dir.mkdirs();
}
fileName = parentPath + File.separator + docName + ".doc";
File outFile = new File(fileName);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
// 生成Word文件到指定路径,而不是直接返回给response里给浏览器下载
template.process(replaceMap, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
// 生成压缩包
public static void writeZip(List<String> files, String zipname) throws IOException {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
String fileName = zipname + ".zip";
OutputStream os = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
ZipOutputStream zos = new ZipOutputStream(os);
byte[] buf = new byte[8192];
int len;
for (int i = 0; i < files.size(); i++) {
File file = new File(files.get(i));
if (!file.isFile()) continue;
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
while ((len = bis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
bis.close();
zos.closeEntry();
}
zos.closeEntry();
zos.close();
// 删除下载的文件
for (int i = 0; i < files.size(); i++) {
File file = new File(files.get(i));
if (!file.isFile()) continue;
file.delete();
}
}
最终效果:
解压后:
版权声明:本文为lllll520520520520520原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。