【问题标题】:How to Export an Excel File using C#如何使用 C# 导出 Excel 文件
【发布时间】:2020-10-29 20:00:47
【问题描述】:

Helo,我已经在 Google 和此处 (StackOverflow) 上进行了搜索,但没有完成任何解决方案。

我的文件夹中有一个 Excel 文件,我需要在我的控制器上创建一个方法来下载此文件。

在我的 React 网站中,我需要将此文件获取到用户计算机。

我尝试使用 ActionResult、FileStreamResult、HttpResponseMessage 等,从具有 File.ReadAllbytes 的文件夹中读取文件,将 Header 放在响应上。

在决赛中我明白​​了。

{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}

并使用此 JavaScript 下载:

var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
                var blob = new Blob([bytes], {
                    type: responseDownloadFile.data.ContentType
                });

                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = responseDownloadFile.data.FileDownloadName;
                document.body.appendChild(link);
                link.click();

但是下载时文件损坏了。

有什么可以帮助我的吗?

【问题讨论】:

标签: c# excel ajax api download


【解决方案1】:

尝试在您的 API 上返回 HttpResponseMessage 类型

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent([file bytes]);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "filename.xlsx"
            };

            return result;

然后在您的前端执行代码:

window.location.href = "link to your api endpoint to download excel";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多