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
Based on the XML of the worksheet, this part:
<x:row r="1" spans="1:37">
<x:c r="A1" t="s">
<x:v />
</x:c>
</x:row>
should not exist outside of the SheetData element. In fact, there appears to be a duplicate, since
<x:row>
<x:c r="A1" t="inlineStr">
<x:is>
<x:t>TestResultFileId</x:t>
</x:is>
</x:c>
</x:row>
also exist. Note that the "actual" header Row has no RowIndex assigned, but according to the CellReference of "A1", this particular row is on row 1.
Note that this:
var rows = sheetData.Elements<Row>().Where(r => r.RowIndex > 1).ToArray();
will probably ignore any Row objects without the RowIndex assigned (I didn't test this though...). Which can happen. Excel should have assigned a value, but any third-party software isn't bound to do so (because the Open XML specs state that RowIndex is an optional attribute).
I don't know why there's a Row object outside of SheetData. Check that the original template Excel file doesn't have this "Row object outside of SheetData object" case. If it does, then the original template file was faulty in the first place.
You might want to consider the option of storing the 1st Row in a separate variable first. Then wipe out all the child elements of SheetData. Then Append() that 1st Row in. This might be easier. You can wipe out children like so (insert bad parenting joke here):
sheetData.RemoveAllChildren();
Best Answer
That error message means that the XML that makes up your excel document is not conforming to the XML Schema and is invalid. You can use the Open XML SDK 2.0 Productivity Tool to see where the issue is located.
I also copied the code from the bottom of your link and got it to work like Chris said in his comment. Does your code look like this below?