我创建了一个生成Excel文件的端点。如果我想要一些其他代码将其发送到不同的端点进行电子邮件发送,或者我想通过在浏览器中手动点击端点来下载Excel文件,它应该用作GET。它正在下载Excel文件,但是当我尝试打开它时,我看到消息“Excel无法打开文件'blahblah',因为文件格式或文件扩展名无效。验证文件是否已损坏且文件扩展名匹配文件的格式。“
收到该错误后,我尝试更改响应内容字段和/或文件扩展名中的MIME类型,错误消失,文件打开时出现以下警告:“文件格式和扩展名”blah blah“不匹配。文件可能已损坏或不安全。除非您信任其来源,否则请不要打开它。无论如何,您要打开它吗?”如果我打开它,文件仍然是空的。
以下是我创建的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());
我尝试添加不同的mime类型,如application / excel。我尝试过使用.xlsx文件扩展名而不是xls。什么都没有真正奏效。我知道ExcelPackage工作簿的工作表实际上有我想要的数据,因为当我调试并将鼠标悬停在对象上时,我会看到我希望将其放入文件中的单元格值。那么我做错了什么?
我已尝试以两种方式生成excelPackage,两者都在使用块内。像这样:
using (var excelPackage = new ExcelPackage())
{
// generate and download excel file
}
也是这样:
using (var excelPackage = new ExcelPackage(new FileInfo(fileName)))
{
// generate and download excel file
}
答案 0 :(得分:4)
我用它将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();