java实现流输出形式导出数据(使用EasyExcel)并打包为zip包

使用EasyExcel实现数据导出以流输出形式并打包为zip包

pom.xml文件导入easyexcel

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>easyexcel</artifactId>
	<version>2.0.5</version>
</dependency>

导出数据的核心代码

@GetMapping("/export")
public void export(ConsumptionDetailQuery query, HttpServletResponse response) {
 	try {
 		String exportRedisFlag = "exportRedisFlag";
        if(redisTemplate.hasKey(exportRedisFlag)) {
            LOGGER.info("导出正在运行,请稍候重试");
            errorResponse(response, "导出正在运行,请稍候重试", 501);
            return;
        }
 		List<RiskIndexExport> exportList;//用来存储查询到的数据
		Sheet sheet1 = new Sheet(1, 0, ExportModel.class);
		sheet1.setSheetName("sheet1");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
		writer.write(exportList, sheet1);
		writer.finish();
		String fileName = "exportName";
		zipOutput(response, out, fileName);
	catch (IOException e) {
        LOGGER.error("导出时写入数据到文件出错" + e.getMessage(), e);
        errorResponse(response, "写入数据到文件出错", 500);
     } finally {
            redisTemplate.delete(exportRedisFlag);
        }
}

zipOutput()方法代码

private void zipOutput(HttpServletResponse response, ByteArrayOutputStream out, String fileName) throws IOException {
        ZipOutputStream zipout = null;
        InputStream inputStream = null;
        try {
            response.setContentType("application/force-download");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName+".zip").getBytes("UTF-8"), "ISO8859-1"));
            inputStream = new ByteArrayInputStream(out.toByteArray());
            zipout = new ZipOutputStream(response.getOutputStream());
            //excel文件写入zip
            zipout.putNextEntry(new ZipEntry(fileName+".xlsx"));
            int len;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) > 0) {
                zipout.write(buf, 0, len);
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            LOGGER.error("zipFiles exception:{}", e.getMessage());
        } finally {
            if (zipout != null) {
                zipout.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

errorResponse方法代码

private void errorResponse(HttpServletResponse response, String message, Integer code) {
        try {
            Map map = new HashMap();
            map.put("code", code);
            map.put("msg", message);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(JSONObject.toJSONString(map).getBytes());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

ExportModel 实体类(需要继承BaseRowModel)

public class ExportModel extends BaseRowModel {

	//注解形式实现标题行
    @ExcelProperty(value = "编号", index = 0)
    private String id;
    
    @ExcelProperty(value = "指标", index = 1)
    private String name;

    @ExcelProperty(value = "年龄", index = 2)
    private String age;
}

有问题大家互相交流

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在Spring Boot中使用EasyExcel导出动态数据为Excel文件的代码如下: 1. 首先,我们需要导入`easyexcel`的依赖。在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.3.0</version> </dependency> ``` 2. 创建一个Excel工具类,用于导出Excel文件。假设我们已经有一个名为`ExcelUtil`的工具类。 ```java import com.alibaba.excel.EasyExcel; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; @Component public class ExcelUtil { public void export(HttpServletResponse response, List<Object> data) throws IOException { // 设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("导出文件", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); // 导出Excel文件 EasyExcel.write(response.getOutputStream(), Object.class).sheet("Sheet1").doWrite(data); } public void exportTemplate(HttpServletResponse response) throws IOException { // 设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); String fileName = URLEncoder.encode("模板文件", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx"); // 导出模板文件 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("template.xlsx"); EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).sheet().doWrite(null); } } ``` 3. 创建一个Controller类,用于处理导出Excel的请求。 ```java import org.springframework.beans.factory.annotation.Autowired; 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.IOException; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/excel") public class ExcelController { @Autowired private ExcelUtil excelUtil; @GetMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { // 模拟动态数据,实际场景中可以根据业务需求获取数据 List<Object> data = new ArrayList<>(); data.add("数据1"); data.add("数据2"); data.add("数据3"); // 导出Excel文件 excelUtil.export(response, data); } @GetMapping("/template") public void exportTemplate(HttpServletResponse response) throws IOException { // 导出Excel模板文件 excelUtil.exportTemplate(response); } } ``` 以上代码演示了使用Spring Boot和EasyExcel导出动态数据为Excel文件的过程。在Controller中,我们可以根据实际业务需求获取数据,并调用`ExcelUtil`中的方法实现导出操作。同时,我们也提供了导出Excel模板文件的方法,以方便用户进行数据录入。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csgogogo_471

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值