基于策略模式的导出
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博客