C# HttpGet 响应给了我一个带有 EPPlus 的空 Excel 文件

Han*_*ror 0 c# mime get file epplus

我创建了一个生成 Excel 文件的端点。它应该用作 GET,以防我想要一些其他代码将其发布到不同的端点以发送电子邮件,或者我只想通过在浏览器中手动点击端点来下载 Excel 文件。它正在下载 Excel 文件,但是当我尝试打开它时,我看到消息“Excel 无法打开文件 'blahblah',因为文件格式或文件扩展名无效。请验证文件是否已损坏且文件扩展名是否正确与文件格式匹配。”

收到该错误后,我尝试更改响应内容字段和/或文件扩展名中的 MIME 类型,错误消失,文件打开并显示以下警告:“文件格式和扩展名”等等等等不匹配。文件可能已损坏或不安全。除非您相信其来源,否则请勿打开它。您仍要打开它吗?” 如果我无论如何打开它,文件仍然是空的。

这是我使用我创建的 ExcelPackage 并将其添加到响应中的代码。

var response = HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats-  officedocument.spreadsheetml.sheet";
var fileName = string.Format("blahblah-{0}.xls",     InstantPattern.CreateWithInvariantCulture("yyyy-dd-M-HH-mm-ss").Format(_clock.Now));
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
response.BinaryWrite(excelPackage.GetAsByteArray());
Run Code Online (Sandbox Code Playgroud)

我尝试添加不同的 mime 类型,如 application/excel。我试过使用 .xlsx 文件扩展名而不是 xls。什么都没有真正奏效。我知道 ExcelPackage 工作簿的工作表实际上包含我想要的数据,因为当我调试并将鼠标悬停在对象上时,我会看到我希望将其写入文件的单元格值。那么我做错了什么?

我已经尝试以两种方式生成 excelPackage,这两种方式都在 using 块内。像这样:

using (var excelPackage = new ExcelPackage())
{
    // generate and download excel file
}
Run Code Online (Sandbox Code Playgroud)

也像这样:

using (var excelPackage = new ExcelPackage(new FileInfo(fileName)))
{
   // generate and download excel file
}
Run Code Online (Sandbox Code Playgroud)

VDW*_*WWD 5

我用它来将 Excel 文件发送到浏览器。

HttpResponse Response = HttpContext.Current.Response;

//first convert to byte array
byte[] bin = excelPackage.GetAsByteArray();

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//add the content type
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

//set the content length, without it, length is set to -1 and could give errors
Response.AddHeader("content-length", bin.Length.ToString());

//add a filename
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".xlsx\"");

//send the file to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)