Excel doesn't want to open XLSX files downloaded through ASP output
I use ASP MVC3 framework, created an Excel file and outputted it using FileResult action with content type " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ".
When attempting to open it Excel just says " file is corrupt and cannot be opened ."
When I open the source generated Excel file that was used to send the output it works without any problems. I also run file comparison on the bytes for both copies and the files are identical. I tried to email the corrupt file to myself and the attachment opens fine.
This leads me to believe it's a problem with headers or some sort of Excel/Windows security config.
If it is the latter, then I need a solution that won't make clients change their security settings.
EDIT - Found the setting:
I've found what setting causes this - " Enable protected view from files originated from the internet " in Excel's Trust Center / Protected View settings.
So I guess the question is - Is there a way for the file to appear trusted?
Here are the response headers:
The action method that makes the output:
[HttpPost]
public virtual FileResult Export()
{
try
{
...
string newFilePath = createNewFile(...);
string downloadedFileName = "Report - " + DateTime.Now.ToString("D") + ".xlsx";
return File(newFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", downloadedFileName);
}
catch (Exception ex)
{
...
}
}
How I create the Excel file:
I have a template XLSX file witch column names and some pivot charts in other sheets. From C# I create a copy of this template and then call SQL Server which outputs data into 1st sheet using OLEDB connector:
set @SQL='insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;Database=' + @PreparedXLSXFilePath + ';'', ''SELECT * FROM [Data$]'') ...
Thanks in advance for any help.
You would need a digital signature in your Excel file. How to do this from code is another question.
More info here:
http://www.delphifaq.com/faq/windows_user/f2751.shtml
链接地址: http://www.djcxy.com/p/46872.html