当我尝试使用 EPPlus 生成 Excel 文件时,Excel 给我以下错误消息:
Excel cannot open the file 'myfilename.xlsx' because the file format or file extension is not valid. Verify the the file has not been corrupted and that the file extension matches the format of the file.
这是我的代码:
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.Position = 0;
您不应该直接写入响应,这不是 MVC 方式。它没有遵循正确的 MVC 管道,而是将您的 Controller 操作代码与 Response 对象紧密耦合。
当您在 File()
中添加文件名作为第三个参数时,MVC 会自动添加正确的 Content-Disposition
header ...因此您不需要手动添加。
简而言之,这就是您想要的:
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);
}
}
关于c# - 使用 EPPlus 生成 excel 文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608547/