java - 使用 Spring Boot 下载 .xls 文件 y Apache POI 不起作用
问题描述
我想实现一种方法,该方法从数据库中下载带有表记录的 .xls 文件。我在没有任何模板的情况下专注于后端,问题是当我运行应用程序和相应的方法时,下载没有开始并且屏幕上“出现”记录
客户服务:
@Override
public ByteArrayInputStream exportData() throws Exception {
String[] columnas = {"Número Cliente", "Nombre", "Apellido", "Dirección", "Activo"};
Workbook workbook = new HSSFWorkbook();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Sheet sheet = workbook.createSheet("Clientes");
Row row = sheet.createRow(0);
for(int i=0; i<columnas.length; i++){
Cell cell = row.createCell(i);
cell.setCellValue(columnas[i]);
}
List<E01_cliente> clientes = (List<E01_cliente>) clienteRepository.findAll();
int initRow = 1;
for(E01_cliente c : clientes){
row = sheet.createRow(initRow);
row.createCell(0).setCellValue(c.getNro_cliente());
row.createCell(1).setCellValue(c.getNombre());
row.createCell(2).setCellValue(c.getApellido());
row.createCell(3).setCellValue(c.getDireccion());
row.createCell(4).setCellValue(c.isActivo());
initRow++;
}
workbook.write(stream);
workbook.close();
return new ByteArrayInputStream(stream.toByteArray());
}
控制器方法:
@GetMapping("/descargar")
public ResponseEntity<InputStreamResource> exportData() throws Exception {
ByteArrayInputStream stream = clienteService.exportData();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Dispotion", "attachment; filename=clientes.xls");
return ResponseEntity.ok().headers(headers).body(new InputStreamResource(stream));
}
实体客户:
@Entity
public class E01_cliente {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int nro_cliente;
private String nombre;
private String apellido;
private String direccion;
private boolean activo;
@OneToMany(mappedBy = "cliente")
@JsonIgnore
private List<E01_factura> facturas;
//Getters and Setters ignored
解决方案
使用Content-Disposition
而不是Content-Dispotion
作为标题
headers.add("Content-Disposition", "attachment; filename=clientes.xls");
推荐阅读
- python - 如何使用 Pandas 在 csv 文件中创建新列,并根据这些列中的值添加数据
- android - 带有 React Native 和 Headless JS 的 Socket IO,无法杀死它
- javascript - NodeJS parallel PostgreSQL query?
- reactjs - 实现 react-select 包时遇到问题
- google-app-engine - app.yaml: max_concurrent_requests available in python flex environment?
- python - 从数据框中返回有关信息的整行
- python - Python-Kruskal Wallis--> Dunn 事后测试
- logstash - 如何在logstash if语句中使用和条件
- python - 使用多处理生成单个字典
- javascript - 使用画布在图像顶部写入文本