产生与EPPlus Excel文件失败 [英] Generating an excel file with EPPlus is failing

查看:758
本文介绍了产生与EPPlus Excel文件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用产生的EPPlus Excel文件,Excel的给我下面的错误信息:

When I try to generate an Excel file using EPPlus, Excel give me the following error message:

Excel无法打开文件myfilename.xlsx',因为文件格式或文件扩展名无效。确认该文件还没有被破坏,该文件扩展名的文件的格式相匹配。

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.

下面是我的code:

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);
    }
}

任何想法,我做错了吗?

Any idea what I'm doing wrong?

推荐答案

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

All you need to do is reset the stream position. stream.Position = 0;

您的不应该直接写入响应,它不是MVC方式。它没有遵循正确的MVC管道,它紧紧地将你的控制器动作code到Response对象。

You shouldn't write directly to the Response, it's not the MVC way. It doesn't follow the correct MVC pipeline and it tightly couples your controller action code to the Response object.

当你添加一个文件名称,如第三个参数文件(),MVC会自动将正确的内容处置头...所以你应该不需要手动添加。

When you add a file name as the 3rd parameter in File(), MVC automatically adds the correct Content-Disposition header... so you shouldn't need to add it manually.

它的短是,这是你想要什么:

The short of it is, this is what you want:

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);
    }
}

这篇关于产生与EPPlus Excel文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆