欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot使用EasyExcel压缩成zip导出多个excel

程序员文章站 2024-03-20 14:24:16
...

以下为kottlin代码
1.controller:

//1.新建zip输出流
val zipOutputStream = ZipOutputStream(response.outputStream)
        try {
            request.isExport = true
            request.exportNum = 1000
            //必须设置limit 否则影响offset的计算
            request.limit = 1000
            var pageNum: Int = 1
            request.pageNum = pageNum
            var data = this.listXxx(request)
            if (data.items.isEmpty()) return
            //分页查询  一页导出一个excel
            while (true) {
                //导出数据处理
      
                var resultList = data.items
                //遍历生成zip中的多个excel
                ExcelUtils.exportZipEasyExcel(
                        zipOutputStream,
                        "导出的excel名字_${Instant.now().toEpochMilli()}.xlsx",
                        "sheetName",
                        XXXDTO::class.java,
                        resultList
                )
                if (data.items.size != request.exportNum) {
                    break
                }
                pageNum ++
                request.pageNum = pageNum
                data = this.listXxx(request)
            }
        } finally {
            zipOutputStream.flush()
            zipOutputStream.close()
            response.outputStream.close()
        }

    }

2.ExcelUtils:

fun <T> exportZipEasyExcel(
                zipOutputStream: ZipOutputStream,
                fileName: String,
                sheetName: String,
                clazz: Class<T>,
                list: List<T>
        ){
            val baos = ByteArrayOutputStream()
            //这里使用alibaba的EasyExcel将分页列表写入baos
            EasyExcel.write(baos, clazz).sheet(sheetName).doWrite(list)
            val content: ByteArray = baos.toByteArray()
            val `is` = ByteArrayInputStream(content)
            val bis = BufferedInputStream(`is`)
            try {
                zipOutputStream.putNextEntry(ZipEntry(fileName));
                var len: Int = 0
                val buf = ByteArray(1024)
                while (bis.read(buf).also { len = it } > 0) {
                //缓冲流中的分页列表写入zip中的一个文件
                    zipOutputStream.write(buf, 0, len)
                }
            }catch (e :Exception) {
                e.printStackTrace()
            }finally {
                zipOutputStream.closeEntry()
                bis.close()
                `is`.close()
                baos.close();//关闭excel输出流
            }
        }

上一篇: 顺序表--C语言描述

下一篇: