【已解决】单个导出的基础上,批量循环导出文件,压缩为tar压缩文件,批量导出

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class ExcelService {

    public void batchExportConfig(List<Long> deviceIds, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TarArchiveOutputStream taos = new TarArchiveOutputStream(baos);
        try {
            final String deviceIds = request.getParameter("deviceIds");
            if (deviceIds == null || deviceIds.isEmpty()) {
                throw new IllegalArgumentException("deviceIds parameter is missing or empty");
            }
            final Long[] deviceIdList = RequestParamUtils.splitToIdArray(deviceIds);

            for (Long deviceId : deviceIdList) {
                // 假设 exportSingleConfig 返回一个字节数组表示 Excel 文件
                byte[] excelBytes = exportSingleConfig(deviceId, request);

         
                final String fileName = "单个文件名字.config";
                TarArchiveEntry entry = new TarArchiveEntry(fileName);
                entry.setSize(excelBytes.length);
                taos.putArchiveEntry(entry);
                // 将 Excel 文件写入 tar 条目
                taos.write(excelBytes);
                taos.closeArchiveEntry();
            }
            taos.finish();
            taos.close();
        } catch (Exception e) {
            log.error("Failed to export config for device", e);
        }

        // 设置响应头
        response.setContentType("application/x-tar");
		// 这样名字不会乱码
        String encodedFileName = URLEncoder.encode("压缩文件名字.tar", StandardCharsets.UTF_8.toString());
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        response.setCharacterEncoding(Charsets.UTF_8.name());

        // 将 tar 文件写入响应流
        IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream());
        response.flushBuffer();
    }

    private byte[] exportSingleConfig(Long deviceId, HttpServletRequest request) {
        // 这里实现单个导出逻辑
        // 返回一个字节数组表示 Excel 文件
        return new byte[0]; // 示例代码,实际需要实现具体的导出逻辑
    }
}

猜你喜欢

转载自blog.csdn.net/wufaqidong1/article/details/144593971
今日推荐