我有来自后端(spring boot)的响应 json:
private byte[] archivoExcel;
private String extension;
private String mime;
我在 Angular 中需要的是获取这个字节[]并将其导出到excel,为此我在 Angular 中的答案json是:
export class RespuestaExportar {
archivoExcel: ArrayBuffer;
extension: string;
mime: string;
}
在我的 component.ts 文件中,我有:
this.reversionesService.getReversionesExportarSeguimiento(this.solicitud).subscribe(res => { this.respuestaExportar=res; let file = new Blob([this.respuestaExportar.archivoExcel], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var fileURL = URL.createObjectURL(file); window.open(fileURL); }
当我运行“导出”按钮时,它正确使用并下载 Excel,但该文件已损坏。我还需要采取进一步的步骤来解决这个问题吗?或者还有另一种选择,因为我需要从后端获取这个字节[]。
最佳答案
我认为您可以从我为后端(SpringBoot)执行的这项服务中进行指导,我以 json 形式发送responseObject
ObjectResponse response = new ObjectResponse();
ByteArrayInputStream in = getExcel();
byte[] array = new byte[in.available()];
in.read(array);
httpStatus = HttpStatus.OK;
response.setResultado(array);
return new ResponseEntity<>(response, httpStatus);
我得到了一个Json响应,其发送数据的结构是,当序列化它时,response.getResult以base64到达,也就是说,已经转换到接收它的客户端。
因此,在我的前端(Angular)中,我继续将其转换为 Blob 并能够处理该文件。
this.subcriber = this.reporteService.generarExcel (). subscribe ((b64Data: any) => {
const byteCharacters = atob (b64Data.result);
const byteNumbers = new Array (byteCharacters.length);
for (let i = 0; i <byteCharacters.length; i ++) {
byteNumbers [i] = byteCharacters.charCodeAt (i);
}
const byteArray = new Uint8Array (byteNumbers);
let blob = new Blob ([byteArray], {type: 'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
const url = window.URL.createObjectURL (blob);
const anchor = document.createElement ('a');
anchor.download = `file.xlsx`;
anchor.href = url;
anchor.click ();
messageService = {
state: false,
messages: null
};
}, (err) => {
this.subcriber.unsubscribe ();
})
希望对你有帮助
关于excel - 从 Angular 中的 byte [] 导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63163634/