Search code examples
downloadexport-to-excelaccess-violationcontent-disposition

Excel .xlsx download - sharing violation error message on Open and Save combination


I've found this question posed a few times, but no definitive answers as yet. Looks like a decent solution would help quite a few people.

So we create an excel file (.xlsx) on the server and download it to the client using content-disposition 'attachment'. The Open Save dialog appears and all works fine if you choose Save, or Open and then Save As... However if you choose Open and then hit the Save... button then Excel hangs for a moment and then presents the message: Your changes could not be saved to 'Export[5].xlsx' because of a sharing violation. Try saving to a different file. then: The file you are trying to open 'F8CAC020.IE5\HM2NBE5C\F8CAC020', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now? then: you finally get the Save As: dialog (assuming you pressed 'Yes').

Code for creating the file is:

Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AppendHeader("content-disposition", "attachment;filename=Export.xlsx")
Response.AddHeader("Content-Length", New System.IO.FileInfo(NewFile).Length)
Response.TransmitFile(NewFile)
Response.Flush()

If you remove the content-disposition header you get the right sort of behaviour in Excel, but with the wrong name and no guarantee that the Excel document will not instead be shown in the browser (depending on client settings). If you press Open and then Save then you get a message: 'default.aspx' is read-only. To save a copy, click OK, then give the workbook a new name in the Save As dialog box.

So the question is how to combine the 2 behaviours into a reasonable one: Get the nice error message directly above, when you try to Open and then Save a downloaded file, but also specify that the document should be downloaded and given a default filename.

Cheers,

James


Solution

  • I believe there is a bug in the IE file download code that does not acknowledge the completed file transfer (download) from the web server, thus leaving a connection to the downloaded (temporary) file open when the save is attempted. That generates the "sharing violation" message. I tried the same code with FireFox and I don't get the same result, which surely leads me to believe this is an IE-specific problem.

    Unfortunately, given that I believe this to be a bug in IE, I don't think there is presently a clean resolution to this issue.