Проблема при загрузке Excel в angular 8 - PullRequest
0 голосов
/ 21 апреля 2020

Я пытаюсь загрузить Excel в angular 8. Код на стороне сервера:

    public HttpResponseMessage GenerateExcel(int id, string userId,string fileName)
    {
        byte[] resultArray = excelBusiness.GenerateExcel(id, userId);
        return this.GetResponseMessage($"Worksheet_{ fileName }.xlsx", resultArray, "application/octet-stream");
    }
    private HttpResponseMessage GetResponseMessage(string fileName, byte[] resultArray, string format)
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new ByteArrayContent(resultArray);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(format);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;
        return response;
    }

И мой сервис на angular 8

  downloadExcel(url: string) {
    let excelPromise = new Promise((resolve, reject) => {
      let body: any = {};
      this._httpHelper.post(url, body, { responseType: "blob" })
        .then((response: any) => {
          return resolve(response);
        })
        .catch((error: any) => {
          return reject(error);
        });
    });
    return excelPromise;
  }

и компонент экспорт

  onMorpheusExcelClick(event) {
    let URL = API_URL ;
    this.showloader = true;
    this._service.downloadExcel(URL)
      .then((res: any) => {
        let filename = 'test.xlsx'
        const blob = new Blob([res.Content], { type: 'application/octet-stream' });
        this.showloader = false;
        const file = new File([blob], filename, { type: 'application/octet-stream' })
        saveAs(file);
      }).catch(e => {
        this.showloader = false;
        this._alertService.showAlert('DownLoad Failed!', 'Close');
      });
  }

Теперь, когда я пытаюсь экспортировать, Excel загружается, но приходит в поврежденной форме. Приходит следующее сообщение:

введите описание изображения здесь

Мне нужно скачать книгу Excel, где внутри я буду поддерживать несколько листов Excel. Я использую File-saver. js (https://www.npmjs.com/package/file-saver/v/1.3.2) для загрузки Excel

1 Ответ

0 голосов
/ 21 апреля 2020

Я думаю, что это может помочь вам

Это верно для Content-Type в заголовке вашего запроса, поскольку вы действительно публикуете formDataForExport через backend.

Но способ обработки ответа кажется неправильно. Предлагаемое ниже решение может помочь:

Предполагается, что если вы ссылаетесь на этот файл-заставку:

https://github.com/Hipparch/file-saver-typescript/blob/master/file-saver.ts

  this.downloadfile().subscribe((resp: any) => {
    const fileSaver: any = new FileSaver();
    fileSaver.responseData = resp.body;
    fileSaver.strFileName = 'testdata.xls';
    fileSaver.strMimeType = 'application/vnd.ms-excel;charset=utf-8';
    fileSaver.initSaveFile();
  });
}

downloadfile() {
  const formDataForExport: FormData = new FormData();
  formDataForExport.append('export', 'ALL');

  return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
    headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' },
    responseType: 'blob',
    observe: 'response'
  });
}```
...