问题描述
当我尝试使用产生的EPPlus Excel文件,Excel的给我下面的错误信息:
When I try to generate an Excel file using EPPlus, Excel give me the following error message:
Excel无法打开文件myfilename.xlsx',因为文件格式或文件扩展名无效。确认该文件还没有被破坏,该文件扩展名的文件的格式相匹配。
下面是我的code:
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);
}
}
任何想法,我做错了吗?
Any idea what I'm doing wrong?
推荐答案
所有你需要做的就是重置流的位置。 stream.Position = 0;
All you need to do is reset the stream position. stream.Position = 0;
您的不应该直接写入响应,它不是MVC方式。它没有遵循正确的MVC管道,它紧紧地将你的控制器动作code到Response对象。
You shouldn't write directly to the Response, it's not the MVC way. It doesn't follow the correct MVC pipeline and it tightly couples your controller action code to the Response object.
当你添加一个文件名称,如第三个参数文件()
,MVC会自动将正确的内容处置
头...所以你应该不需要手动添加。
When you add a file name as the 3rd parameter in File()
, MVC automatically adds the correct Content-Disposition
header... so you shouldn't need to add it manually.
它的短是,这是你想要什么:
The short of it is, this is what you want:
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);
}
}
这篇关于产生与EPPlus Excel文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!