用EPPlus生成Excel文件失败

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

Excel无法打开文件“myfilename.xlsx”,因为文件格式或文件扩展名无效。 validation文件是否已损坏,文件扩展名是否与文件格式匹配。

这是我的代码:

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的位置。 stream.Position = 0;

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

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

你的代码不会显示正在写入HttpResponse stream – 大概是在你没有发布的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(); 

与乔的回答类似,我仍然需要调用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(); }