压缩文件中的Excel下载



可以调用以下api下载为.xlsx.

我想在.zip文件中下载excel文件

@ResponseBody
@RequestMapping(value = "/excelDownload", method = {RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<Resource> excelDownload() throws Exception {
ResponseEntity<byte[]> entity = null;
ResponseEntity<Resource> excelFile = null;
try {
HashMap<String, String> param = new HashMap<String, String>();
param = (HashMap<String, String>) session.getAttribute("mySession");
List<BranchInfoDTO> BranchInfoDTOList = new ArrayList<>();
try {
BranchInfoDTOList = shopInfoService.selectMyListExcelDownload(param);
} catch (Exception e) {
e.printStackTrace();
}
List<List<String>> dataList = getDownloadData(BranchInfoDTOList);
// the dataList part has no problem at the moment
String folderName = getSessionUser().getName() + DateUtil.date2String(new Date(), DateUtil.YYYYMMDD_HHMMSS);
String baseDirPath = tempDirPath + File.separator + folderName;
InputStreamResource file = new InputStreamResource(ExcelHelper.downloadToExcel2(dataList)); // ExcelHelper.java will be seen below 
excelFile = ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + folderName + ".xlsx")
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(file);
} catch (Exception e) {
System.out.print(e);
throw e;
}
return excelFile;
}

以下静态函数位于ExcelHelper.java 中

public static ByteArrayInputStream downloadToExcel2(List<List<String>> dataList) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream resourceAsStream = new FileInputStream(PROXY_FORMAT_LOCAL);
Workbook workBook = new XSSFWorkbook(resourceAsStream);
Sheet sheet = workBook.getSheetAt(0);
// Data
int rowIdx = 1;
for (List<String> stringList : dataList) {
Row row = sheet.createRow(rowIdx++);
System.out.println("row = " + row);
for (int i = 0; i < stringList.size(); i++) {
row.createCell(i).setCellValue(stringList.get(i));
}
}
workBook.write(out);
return new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
throw new RuntimeException("fail to import data to Excel file: " + e.getMessage());
}
}

存在实体声明为ResponseEntity<byte[]>我想作为ResponseEntity<byte[]>它用于zip文件。

例如

ResponseEntity<byte[]> entity = ExcelFileInsideZip(excelFile);
return entity;

或者可能有其他方法来学习一些东西感谢

使用ZipOutputStream,例如

ByteArrayInputStream bis = ExcelHelper.downloadToExcel2(...);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(bos);
ZipEntry zipEntry = new ZipEntry("excel-file-name");
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while((length = bis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();
return new ByteArrayInputStream(bos.toByteArray());

并调整响应内容类型

.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))

.contentType(MediaType.parseMediaType("application/zip"))

https://www.baeldung.com/java-compress-and-uncompress

最新更新