首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用C#导出Excel文件

如何使用C#导出Excel文件
EN

Stack Overflow用户
提问于 2020-10-30 04:00:47
回答 1查看 76关注 0票数 0

Helo,我已经搜索了谷歌和这里(StackOverflow),但没有任何解决方案我完成。

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

在我的React Web站点中,我需要将此文件发送到用户计算机。

我试着使用ActionResult,FileStreamResult,HttpResponseMessage和其他,用File.ReadAllbytes从文件夹中读取文件,把头放在响应上。

在期末考试中我得到了这个。

代码语言:javascript
运行
复制
{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}

并使用此JavaScript下载:

代码语言: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();

但下载时文件已损坏。

有谁能帮我吗?

EN

回答 1

Stack Overflow用户

发布于 2020-10-30 13:34:43

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

代码语言:javascript
运行
复制
                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;

在你的前端执行代码:

代码语言:javascript
运行
复制
window.location.href = "link to your api endpoint to download excel";
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64598440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档