下面的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。我想作为ResponseEntity返回,这是用于zip文件的。
例如。
ResponseEntity<byte[]> entity = ExcelFileInsideZip(excelFile);
return entity;或者还有其他的方法来学习,谢谢
发布于 2022-11-04 11:09:32
使用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://stackoverflow.com/questions/74313193
复制相似问题