簡體   English   中英

下載並將 c# excel 字節數組轉換為 javascript blob

[英]Download and convert c# excel byte array to javascript blob

我正在使用 POST 方法來獲取 excel 文件的字節數組

c#服務器端實現:

 downloadExcel() {
    ....
    FileResultDto fileResultDto = new FileResultDto
    {
       Data = ExcelHelper.CreateExcelFile(excelFile) //Data contains the byte array
    };

    return new JsonHttpResponseMessage(JsonConvert.SerializeObject(fileResultDto));
}

創建Excel文件():

public byte[] CreateExcelFile(ExcelFile excelFile)
    {
        try
        {
            #region Validation

            if (excelFile == null)
            {
                throw new ArgumentNullException(nameof(excelFile));
            }

            #endregion

            byte[] bytes;

            using (ExcelPackage excelPackage = new ExcelPackage())
            {
                for (int i = 1; i <= excelFile.Worksheets.Count; i++)
                {
                    Worksheet worksheet = excelFile.Worksheets[i - 1];

                    excelPackage.Workbook.Worksheets.Add(worksheet.Name);

                    ExcelWorksheet currentExcelWorksheet = excelPackage.Workbook.Worksheets[i];

                    if (excelFile.HasLogoTemplate)
                    {
                        byte[] imageBytes = Convert.FromBase64String(LogoBase64);

                        Image image;
                        using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                        {
                            image = Image.FromStream(ms, true);
                        }

                        ExcelPicture picture = currentExcelWorksheet.Drawings.AddPicture("Logo", image);

                        picture.SetPosition(0, 4, 0, 10);

                        currentExcelWorksheet.Row(1).Height = 50;
                    }

                    SetColumnsWidths(currentExcelWorksheet, worksheet);

                    WriteHeaderRow(currentExcelWorksheet, worksheet.HeaderRow);

                    WriteCells(currentExcelWorksheet, worksheet.Cells);
                }

                #region Set Excel Stream

                bytes = excelPackage.GetAsByteArray();

                #endregion
            }

            return bytes;
        }
        catch (Exception exception)
        {
            throw new Exception("There was an error on excel export. Exception: ", exception);
        }
    }

前端實現:

public downloadExcel(): void {

    this.myRepository.downloadExcel(this.postData).then(result => {
        var byteArray = new Uint8Array(result.data.data);

        var a = window.document.createElement('a');
        a.href = window.URL.createObjectURL(new Blob([byteArray], { type: "application/octet-stream" }));

        a.download = "test.xlsx";

        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }, error => {
        console.log(error);
    });
}

顯然,創建的 blob 文件似乎已損壞。 問題可能出在哪里的任何建議?

最后使用'arraybuffer'作為http請求的響應類型解決了問題。

let requestConfiguration: ng.IRequestConfig = {
        cache: ...,
        data: ...,
        headers: ...,
        method: ...,
        url: ...,
        responseType: 'arraybuffer'
    };        

    let promise: ng.IPromise<any> = this.$http(requestConfiguration);

在 Angular 中也是如此。 這可能對你有幫助

downloadExcel(){
        this.downloadAttachment(filename).subscribe(res => {
          let Res=res;
          const downloadedFile = new Blob([Res], { type: Res.type });
                const a = document.createElement('a');
                a.setAttribute('style', 'display:none;');
                document.body.appendChild(a);
                a.download = attachment.filename;
                a.href = URL.createObjectURL(downloadedFile);
                a.target = '_blank';
                a.click();
                document.body.removeChild(a);
        },
        err=>{
          throw err;
        })
  }
downloadAttachment(filename){
      this.httpOptions = {
        reportProgress: true,
        responseType: "blob"
      };
      return this.http.get(API_URL, this.httpOptions).pipe(
        map(response => response),
        catchError(this.handleError<any>(isShowError)),
        finalize(() => {

        })
      );    
  }

C# 代碼

var res=DownloadAttachment(filename);
if (res == null)
   return Content("filename not present");
return  File(res, Utility.GetContentType(filename), filename);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM