Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In Window Form while downloading or opening an excel file, a warning is shown each time "The file format and extension of filenameName don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"

How can I prevent this warning?

What I have tried:

The warning is appearing even after changing extension from .xls to .xlsx.

Code I am using:-

Response.Clear();
Response.ContentType = "application/x-msexcel"; 
Response.AddHeader("Content-Disposition", "attachment; filename=File.xls");
Response.ContentEncoding = Encoding.UTF8; 
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
div1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
Posted
Updated 31-Dec-18 5:27am
v2
Comments
F-ES Sitecore 31-Dec-18 9:04am    
You could try a different MIME type (ContentType), google "xlsx mime type". However the problem might be simply that you are sending html from "div1" and telling the browser that's an xlsx file, but it isn't, it's html.
Mehdi Gholam 31-Dec-18 9:07am    
Html files are not XLS files hence the error, use "text/html"
TechieeGeek 2-Jan-19 5:45am    
Changing the extension didn't solve any problem. Getting same message.

1 solution

You're got a mime type of "application/x-msexcel", but the content of the file your writing is HTML, NOT A VALID EXCEL FILE.

Just putting something that looks like a sheet in Excel into a file does NOT make it an Excel file.

You're going to have to either change the mime type to something more appropriate for HTML content, like "text/html", or use a library, like OpenXML or ClosedXML, to generate actual Excel content. Which one of these things you do depends on what your app is expecting for content in the file.
 
Share this answer
 
Comments
TechieeGeek 2-Jan-19 4:55am    
I tried changing the MIME type to HTML as suggested. Still I am getting the same error while opening the excel. So in such is using the external library the only solution.
Dave Kreskowiak 2-Jan-19 12:17pm    
That's because an HTML file is NOT an Excel file. What you wrote to the file is not something Excel can understand. You have to use a library to write appropriate content to the file so Excel can read it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900