import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping("/api/excel")
public class ExcelController {
@GetMapping("/download-zip")
public void downloadZip(HttpServletResponse response) throws IOException {
// 设置响应头
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=excel_files.zip");
// 创建ZIP输出流
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
// 假设我们有多个Excel数据列表
List<List<String[]>> excelDataList = getExcelDataLists(); // 你需要实现这个方法
for (int i = 0; i < excelDataList.size(); i++) {
List<String[]> excelData = excelDataList.get(i);
// 生成Excel文件内容
byte[] excelBytes = ExcelGenerator.generateExcel(excelData);
// 创建ZIP条目
ZipEntry entry = new ZipEntry("file" + (i + 1) + ".xlsx");
zos.putNextEntry(entry);
// 写入Excel文件到ZIP条目
zos.write(excelBytes);
zos.closeEntry();
}
}
}
private List<List<String[]>> getExcelDataLists() {
// 返回模拟的数据列表
// 这里你需要根据实际情况返回实际的数据
return List.of(
List.of(new String[]{"Header1", "Header2"}, new String[]{"Data1", "Data2"}),
List.of(new String[]{"HeaderA", "HeaderB"}, new String[]{"DataA", "DataB"})
);
}
}
|