简体   繁体   English

将blob转换为Excel文件并下载,文件无法打开

[英]convert blob to Excel file and download, file cannot be open

I have an api which return below response, which contain the excel file content.我有一个 api,它返回下面的响应,其中包含 excel 文件内容。

API返回数据

So now I need to convert them into excel file and download for the user.所以现在我需要将它们转换为 excel 文件并为用户下载。

Here is the api function这是api函数

   [HttpGet]
    [IgnoreAntiforgeryToken]
    public async Task<IActionResult> DownloadLoadedTrnFile(string S3Path)
    {
        try
        {
            string bucket = "taurus-" + GetEnvironmentSettings() + "-trn";
            string fileName = "";
            string[] fileStr = S3Path.Split('-');
            if (fileStr.Count() > 0)
            {
                fileName = fileStr.Last();
            }
            Stream responseStream = await _imageStore.GetImage(bucket, S3Path);
            if (responseStream == null)
                return NotFound();
            using (MemoryStream ms = new MemoryStream())
            {
                responseStream.CopyTo(ms);

                var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()), MimeTypesMap.GetMimeType(S3Path), fileName);
                return Ok(finalResult);
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, "Error in downloading file.");
        }
    }





     public async Task<Stream> GetImage(string bucketName, string objectKey)
    {
        GetObjectRequest originalRequest = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = objectKey
        };
    
        try
        {
            GetObjectResponse response = await S3Client.GetObjectAsync(originalRequest);

            // AWS HashStream doesn't support seeking so we need to copy it back to a MemoryStream
            MemoryStream outputStream = new MemoryStream();
            response.ResponseStream.CopyTo(outputStream);

            outputStream.Position = 0;

            return outputStream;
        }
        catch (AmazonS3Exception ex)
        {
            // Not found if we get an exception
            return null;
        }
    }

I have such function in the front-end as below,我在前端有这样的功能,如下所示,

      function saveTextAsFile(data, filename, contentType) {
        if (!data) {
            console.error('Console.save: No data')
            toastr.error("No data received from server");
            return;
        }

        if (!filename) filename = 'noname.xlsx';

        var blob = new Blob([s2ab(atob(data))], {
            type: contentType
        });


        var a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = filename;
        a.click();
    }

and function和功能

     function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }

This function is working fine with excel that only has normal text.此功能在只有普通文本的 excel 中运行良好。 However, this excel i am trying to download, it has rich content such as color border, dropdown, multiple sheets.但是,我正在尝试下载这个excel,它具有丰富的内容,例如彩色边框、下拉菜单、多张表格。

When I try to use this same function to download the excel file, it throw me this error:当我尝试使用相同的函数下载 excel 文件时,它抛出了这个错误:

在此处输入图片说明

To help you more understand my problem, here is t he API HTTP CAll为了帮助您更了解我的问题,这里是 API HTTP CAll

在此处输入图片说明

在此处输入图片说明

I have try to search solution online but there is no luck.我尝试在线搜索解决方案,但没有运气。 I actually do not understand what is the problem here.我实际上不明白这里有什么问题。 Anything will help thanks.任何事情都会有所帮助谢谢。

Thanks for all the replies and make my head around a little bit finally I fixed this issue.感谢您的所有回复,并让我稍微了解一下,最后我解决了这个问题。

Well, found the problem with it is because in the API I wrap that inside UTF-8.好吧,发现它的问题是因为在 API 中我将它包装在 UTF-8 中。 however, it (Excel) shouldn't be wrapped in UTF-8.但是,它 (Excel) 不应包含在 UTF-8 中。 only If I was downloading a csv file.仅当我正在下载 csv 文件时。

   var finalResult = File(System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()), 
   MimeTypesMap.GetMimeType(S3Path), fileName);

Changed to变成

   var finalResult = File(ms.ToArray(), MimeTypesMap.GetMimeType(S3Path), fileName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM