java用springboot写一个controller接口通过restful调用获取excel文件,下载到本地
时间: 2024-11-09 08:17:24 浏览: 45
pdf下载接口,输出流文件下载
5星 · 资源好评率100%
在Spring Boot项目中,你可以使用`Spring MVC`和`Apache POI`库来创建一个Controller接口,该接口用于通过RESTful API返回Excel文件并供客户端下载。以下是简单的步骤:
1. 添加依赖:
在`pom.xml`中添加Spring Web、Spring MVC和Apache POI的依赖:
```xml
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <!-- 如果需要数据库支持,可以加上这行 -->
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
</dependencies>
```
2. 创建Excel生成服务:
```java
@Service
public class ExcelGeneratorService {
// 使用CSV或XLSX生成数据的方法,这里仅展示CSV示例
public byte[] generateExcelData(List<String[]> data) throws IOException {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream));
for (String[] row : data) {
writer.writeNext(row);
}
writer.flush();
return outputStream.toByteArray();
}
}
}
```
3. 创建Controller接口:
```java
@RestController
public class ExcelController {
private final ExcelGeneratorService excelGeneratorService;
public ExcelController(ExcelGeneratorService excelGeneratorService) {
this.excelGeneratorService = excelGeneratorService;
}
@GetMapping("/download-excel")
public ResponseEntity<byte[]> downloadExcelFile(@RequestParam("data") List<String[]> dataList) throws IOException {
byte[] fileContent = excelGeneratorService.generateExcelData(dataList);
// 设置响应头,告诉浏览器这是一个下载请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.csv");
return ResponseEntity.ok().headers(headers).body(fileContent);
}
}
```
4. 测试API:
通过发送GET请求到`/download-excel?data={your_data_array}`来触发下载。
阅读全文