使用EPPlus生成excel文件失败

时间:2012-03-07 20:26:43

标签: 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);
    }
}

知道我做错了吗?

3 个答案:

答案 0 :(得分:28)

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

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

当您在File()中添加文件名作为第3个参数时,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);
    }
}

答案 1 :(得分: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();

答案 2 :(得分:2)

与Joe的答案类似,我仍然需要致电Response.ClearHeaders()

   protected void btnDownload_Click(object sender, EventArgs e)
   {

       ExcelPackage pck = new ExcelPackage();
       var ws = pck.Workbook.Worksheets.Add("Sample2");

       ws.Cells["A1"].Value = "Sample 2";
       ws.Cells["A1"].Style.Font.Bold = true;
       var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
       shape.SetPosition(50, 200);
       shape.SetSize(200, 100);
       shape.Text = "Sample 2 outputs the sheet using the Response.BinaryWrite method";
       Response.Clear();    
       Response.ClearHeaders();
       Response.BinaryWrite(pck.GetAsByteArray());
       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
       Response.AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx");
       Response.End();
  }