2

I have the response json from the backend (spring boot):

private byte[] archivoExcel;
private String extension;
private String mime;

What I need in angular is to get this byte [] and export it to excel, for this my answer json in angular is:

export class RespuestaExportar {
    archivoExcel: ArrayBuffer;
    extension: string;
    mime: string;
}

and in my component.ts file I have:

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); }

When I run the 'export' button, it consumes correctly, and it downloads the excel, but this file is damaged. Do I need one more step to solve it? or there is another alternative, since I need to get this byte [] from the backEnd.

jpcruz
  • 21
  • 1
  • 2

1 Answers1

1

I think you can guide yourself from this service that I perform for my backend (SpringBoot) I send a responseObject as json

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);

and I get a Json response with the structure that sent the data is that when serializing it, the response.getResult arrives in base64, that is, already transformed to the client that receives it.

So in my frontend (Angular) I proceed to transform it into a Blob and be able to work the file.

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 ();
})

I hope it helps you