easyexcel导出的尝试

基于策略模式的导出

1.创建导出策略接口

public interface ExportStrategy {
    void export(List<?> data);
}

2.实现不同策略模式

public class UserExportStrategy implements ExportStrategy {
    @Override
    public void export(List<?> data, HttpServletResponse response) {
        // 使用 EasyExcel 导出用户信息
        EasyExcel.write(response.getOutputStream(), User.class)
                 .sheet("用户信息")
                 .doWrite(data);
    }
}

注:对于springboot2.5之前的sevlet依赖是

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

2.5以后得是

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>5.0.0</version> <!-- 确保版本正确 -->
    <scope>provided</scope>
</dependency>

3.创建策略上下类

public class ExportContext {
    private ExportStrategy exportStrategy;

    public ExportContext(ExportStrategy exportStrategy) {
        this.exportStrategy = exportStrategy;
    }

    public void executeExport(List<?> data, HttpServletResponse response) {
        exportStrategy.export(data, response);
    }
}

4.使用

@RestController
@RequestMapping("/export")
public class ExportController {

    @GetMapping("/exportData")
    public void exportData(@RequestParam String exportType, HttpServletResponse response) {
        ExportStrategy strategy;
        
        // 根据 exportType 动态选择策略
        if ("user".equals(exportType)) {
            strategy = new UserExportStrategy();
        } else if ("order".equals(exportType)) {
            strategy = new OrderExportStrategy();
        } else {
            throw new IllegalArgumentException("未知的导出类型");
        }

        // 使用策略上下文进行导出
        ExportContext context = new ExportContext(strategy);
        List<?> data = fetchData(exportType); // 根据类型获取不同的数据
        context.executeExport(data, response);
    }

    // 模拟获取数据的方法
    private List<?> fetchData(String exportType) {
        if ("user".equals(exportType)) {
            return getUserData();
        } else if ("order".equals(exportType)) {
            return getOrderData();
        }
        return Collections.emptyList();
    }

    // 获取用户数据
    private List<User> getUserData() {
        // 查询用户数据
        return new ArrayList<>();
    }

    // 获取订单数据
    private List<Order> getOrderData() {
        // 查询订单数据
        return new ArrayList<>();
    }
}

问题,axiso无法解决导出的问题

解决办法:EasyExcel + Vue +Springboot 前后端联动,快捷导出Excel文件_vue2 和 easyexcel实现excel导出-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值