gpt4 book ai didi

asp.net-mvc-3 - 从 MemoryStream 返回时,ASP.net MVC ActionResult 损坏了 excel 文件

转载 作者:行者123 更新时间:2023-12-02 07:55:20 25 4
gpt4 key购买 nike

我的 Controller 中有以下操作

public ActionResult DownloadExcel()
{
//create and populate Excel file here
C1XLBook testBook = new C1XLBook();
//populate it here

MemoryStream ms = new MemoryStream();
testBook.Save(ms, FileFormat.Biff8);

return File(ms, "application/ms-excel", "test-file.xls");
}

打开文件时,我收到 Excel 消息,指出该文件与扩展名不匹配,并且文件打开时已损坏。

如果我将文件保存在硬盘上并从那里返回它,一切都很好:

return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls");

我最初认为保存函数在将其保存到 MemoryStream 时会损坏它,因此我保存并重新加载它,并且很好地传回给用户 - 当保存在硬盘驱动器上并从那里返回时,而不是比来自 MemoryStream

有什么想法吗?我不太喜欢将文件保存在硬盘上......此外我应该能够将其保存到 MemoryStream 中并从那里返回它?

我的一个预感是,也许 MemoryStream 不应该用于返回 MVC 中的文件,因为每个请求都是隔离的?

最佳答案

也许您需要在将内存流传递给结果之前先倒回内存流(设置 ms.Position = 0;)?调用 Save 后,其位置将位于末尾,而不是开头。

关于asp.net-mvc-3 - 从 MemoryStream 返回时,ASP.net MVC ActionResult 损坏了 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9085281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com