c# - 使用 EPPlus 生成 excel 文件失败

标签 c# asp.net-mvc excel epplus

当我尝试使用 EPPlus 生成 Excel 文件时,Excel 给我以下错误消息:

Excel cannot open the file 'myfilename.xlsx' because the file format or file extension is not valid. Verify the the file has not been corrupted and that the file extension matches the format of the file.

这是我的代码:

public ActionResult Index()
{
    using (ExcelPackage package = new ExcelPackage())
    {
        // I populate the worksheet here.  I'm 90% sure this is fine
        // because the stream file size changes based on what I pass to it.

        var stream = new MemoryStream();
        package.SaveAs(stream);

        string fileName = "myfilename.xlsx";
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        var cd = new System.Net.Mime.ContentDisposition
        {
            Inline = false,
            FileName = fileName
        };
        Response.AppendHeader("Content-Disposition", cd.ToString());
        return File(stream, contentType, fileName);
    }
}

知道我做错了什么吗?

最佳答案

您需要做的就是重置流位置。 stream.Position = 0;

不应该直接写入响应,这不是 MVC 方式。它没有遵循正确的 MVC 管道,而是将您的 Controller 操作代码与 Response 对象紧密耦合。

当您在 File() 中添加文件名作为第三个参数时,MVC 会自动添加正确的 Content-Disposition header ...因此您不需要手动添加。

简而言之,这就是您想要的:

public ActionResult Index()
{
    using (ExcelPackage package = new ExcelPackage())
    {
        // I populate the worksheet here.  I'm 90% sure this is fine
        // because the stream file size changes based on what I pass to it.

        var stream = new MemoryStream();
        package.SaveAs(stream);

        string fileName = "myfilename.xlsx";
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        stream.Position = 0;
        return File(stream, contentType, fileName);
    }
}

关于c# - 使用 EPPlus 生成 excel 文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608547/

相关文章:

c# - .NET 中的货币格式在金额和货币之间提供空白

c# - 如何在 .net 中将 json 解析为 html

html - mvc razor with @html.actionurl 在数据库中存储 HTML

jquery - ASP.NET MVC 5 垂直表头

excel - 支持 ISBLANK 和 IF 语句

vba - 使用 vba 在公式前面插入撇号

c# - String.Format() 时间跨度与日期时间

c# - 为什么我的 C# 应用程序在此 REST 请求上会失败,但通过浏览器可以正常运行?

c# - BackgroundWorker 进程需要引发要在主 (UI) 线程上处理的自定义事件

xml - Excel XML 2003-2004 格式到底是什么?