繁体   English   中英

如何使用 C# 导出 Excel 文件

[英]How to Export an Excel File using C#

Helo,我已经在谷歌和这里 (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();

但下载时文件已损坏。

任何人都可以帮助我吗?

尝试在您的 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";

暂无
暂无

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

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