导出操作流程
- 一对多数据导出到 Excel 内
- 数据关联的图片需要导出到文件夹
- 将 Excel 文件、文件夹打包成 Zip 压缩包并写入接口响应流
相关依赖
- Minio
- EasyPOI1
实现代码
导出 zip 压缩包结构
export.zip├── export.xlsx # Excel 文件直接放在 ZIP 的根目录└── file/ ├── name1/ │ ├── image1.jpg # 商品1的图片文件 │ └── image2.jpg └── name2/ ├── image3.jpg # 商品2的图片文件 └── image4.jpg
关键代码(文件流写入 Zip)
ByteArrayOutputStream baos = new ByteArrayOutputStream();ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())// create ZIP entryZipEntry zipEntry = new ZipEntry("export.xlsx");zos.putNextEntry(zipEntry);
// Excel write to ZIPzos.write(baos.toByteArray());zos.closeEntry();
具体实现
1. 导出 Excel 实体类
public class ExportData { @Excel(name = "名称", needMerge = true) private String name; @ExcelCollection(name = "子数据") private List<ExportDataChildren> children;}
2. 导出子数据类
public class ExportDataChildren { @Excel(name = "名称") private String name;}
3. 文件类
public class ExportFile { // minio url private String url;}
4. 业务代码
class ExportDataService {
public void exportDataZip(HttpServletResponse response) { // get export data List<ExportData> exportList = getExportData(); try (Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExportData.class, exportList); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { // Workbook write to ByteArrayOutputStream workbook.write(baos);
// create ZIP entry ZipEntry zipEntry = new ZipEntry("export.xlsx"); zos.putNextEntry(zipEntry);
// Excel write to ZIP zos.write(baos.toByteArray()); zos.closeEntry();
// export file exportList.forEach(exportData -> { List<ExportFile> exportFileList = getExportFile(); exportFileList.forEach(exportFile -> { try (InputStream inputStream = download(exportData.getUrl())) { byte[] bytes = IoUtil.readBytes(inputStream); String folderPath = "file/" + exportData.getName() + "/"; String name = FileUtil.getName(exportFile.getUrl()); ZipEntry entry = new ZipEntry(folderPath + name); zos.putNextEntry(entry); zos.write(bytes); zos.closeEntry(); } catch (Exception e) { log.error("export file error: {}", e.getMessage()); } }); });
zos.finish(); response.flushBuffer(); } catch (Exception e) { log.error("export zip error: {}", e.getMessage()); } response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"export.zip\""); }
// get file InputStream public InputStream download(String url) { try { return minioClient.getObject( GetObjectArgs.builder() .bucket(YOUR_BUCKET) .object(url) .build() ); } catch (Exception e) { log.error("download file error", e); throw new BusinessException("文件下载异常"); } }
public List<ExportData> getExportData() { // 获取数据库数据 }
public List<ExportFile> getExportFile() { // 获取数据库文件地址 }
}