Excel and “unreadable content” when creating an Open XML spreadsheet with MemoryStream

excelmemorystreamopenxmlopenxml-sdkxml

When creating an Excel spreadsheet using the Open XML SDK v2.0, our Excel output initially worked successfully for a number of months. Recently Excel (all versions) began to complain about "Excel found unreadable content in 'zot.xlsx'. Do you want to recover the contents of this workbook?". We are creating the file in a web application, using a MemoryStream as the store, which is then sent as a byte[] in an HTTP response with a MIME type of "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". The unzipped contents of a bad file were identical to the unzipped contents of a file without errors.

Best Answer

We chased this down for too many hours, picking up a couple of red herrings along the way, but in the end, resolved that the bad file was different in one respect. The file length was different. Before returning the MemoryStream and writing the byte[] to the HTTP response, ensure that you truncate the MemoryStream so that its capacity and length are the same, using a simple stream.Capacity = (int)stream.Length;.

It appears that Excel now detects the extra content in the file as a security risk as 'unreadable content' and throws the annoying error, when in the past it would accept the risk.

Note: answer taken from original poster, who previously had the answer in his question

Related Topic