使用EPPlus生成excel文件失败

Mat*_*nde 14 c# asp.net-mvc excel epplus

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

Excel无法打开文件'myfilename.xlsx',因为文件格式或文件扩展名无效.验证文件是否已损坏,以及文件扩展名是否与文件格式匹配.

这是我的代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

知道我做错了什么吗?

Cha*_*ino 28

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

不应该直接写回应,它不是MVC的方式.它不遵循正确的MVC管道,它将控制器操作代码紧密耦合到Response对象.

当您添加文件名作为第3个参数时File(),MVC会自动添加正确的Content-Disposition标题...因此您不需要手动添加它.

缺点是,这就是你想要的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*Joe 10

您的代码未显示stream正在写入HttpResponse- 可能是在File您尚未发布的方法中完成的.

一种有效的方法如下:

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader(
            "content-disposition", String.Format(CultureInfo.InvariantCulture, "attachment; filename={0}", fileName));
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
Run Code Online (Sandbox Code Playgroud)