用Sping boot完成导出的案例
以下是使用Spring Boot完成导出的示例代码:
- 首先,需要引入相关的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
- 创建一个控制器类,用于处理导出请求:
@RestController
public class ExportController {
@GetMapping("/export")
public ResponseEntity<ByteArrayResource> export() {
// 创建一个Excel文档
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 写入数据
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("姓名");
headerRow.createCell(1).setCellValue("年龄");
Row dataRow1 = sheet.createRow(1);
dataRow1.createCell(0).setCellValue("张三");
dataRow1.createCell(1).setCellValue(20);
Row dataRow2 = sheet.createRow(2);
dataRow2.createCell(0).setCellValue("李四");
dataRow2.createCell(1).setCellValue(25);
// 将Excel文档转换为字节数组
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = outputStream.toByteArray();
// 创建一个字节数组资源对象,用于返回给客户端
ByteArrayResource resource = new ByteArrayResource(bytes);
// 设置响应头信息
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export.xlsx");
// 返回响应对象
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(bytes.length)
.body(resource);
}
}
- 在启动类中添加注解@EnableAutoConfiguration,启用自动配置功能。
@SpringBootApplication
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 启动应用程序,访问http://localhost:8080/export,即可下载一个名为export.xlsx的Excel文件。
这是一个简单的示例,你可以根据实际需求进行修改和扩展
原文地址: http://www.cveoy.top/t/topic/egKG 著作权归作者所有。请勿转载和采集!