简体   繁体   English

下载并将 c# excel 字节数组转换为 javascript blob

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

I am using a POST method to get a byte array of an excel file我正在使用 POST 方法来获取 excel 文件的字节数组

c# server side implementation: c#服务器端实现:

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

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

CreateExcelFile():创建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);
        }
    }

front end implementation:前端实现:

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

Apparently the created blob file it seems to be corrupted.显然,创建的 blob 文件似乎已损坏。 Any suggestions where the problem can be?问题可能出在哪里的任何建议?

Finally the problem solved using 'arraybuffer' as the response type of the http request.最后使用'arraybuffer'作为http请求的响应类型解决了问题。

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

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

The same is done in Angular.在 Angular 中也是如此。 This might be help you这可能对你有帮助

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# Code 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.

相关问题 如何将 javascript 中的字节数组转换为 angular 中的 blob? - How to convert byte array to blob in javascript for angular? 如何仅使用 javascript 将 blob url 转换为字节数组 - How to convert blob url to a byte array using javascript only 将字符串从 C# 发送到客户端并转换为 Uint8Array 类型的字节数组,然后转换为 blob 以打开 excel 文件。 参与的柯基犬 - sending string from C# to client and converting into Uint8Array type byte array and then into blob to open excel file. Corgi Involved C# 字节数组到 Javascript Blob 以创建和自动下载 PDF 文件 - C# Bytes array to Javascript Blob to create and auto download PDF file 使用Java下载图像并将其转换为Blob - Download image with Javascript and convert it to a Blob 将C#字节数组传递给javascript - pass C# byte array to javascript 是否可以将字节数组/流转换为JavaScript中的Word,Excel,PDF等文件 - Is it possible to convert byte array/stream to files such as Word,Excel, PDF in JavaScript 如何将javascript缓冲区转换为c / c ++ API的字节数组? - How to convert javascript Buffer to array of byte for c/c++ API? 将C#数组转换为javascript数组 - Convert c# array to javascript array 在JavaScript中将字节数组转换为二进制 - Convert Byte array to Binary in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM