微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用C#导出Excel文件

如何解决如何使用C#导出Excel文件

您好,我已经在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();

但是下载时文件已损坏。

有什么可以帮助我的吗?

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。