2

Closed

InvalidOperationException when loading an Excel sheet with a funky comment.

description

See attached Excel sheet. When loading this sheet with ClosedXML, I receive the following error:

InvalidOperationException: Sequence contains no matching element

at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func2 predicate)
at ClosedXML.Excel.XLWorkbook.LoadSpreadsheetDocument(SpreadsheetDocument dSpreadsheet) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 334
at ClosedXML.Excel.XLWorkbook.LoadSheets(String fileName) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 47
at ClosedXML.Excel.XLWorkbook.Load(String file) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 36
at ClosedXML.Excel.XLWorkbook..ctor(String file, XLEventTracking eventTracking) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook.cs:line 626
at ClosedXML.Excel.XLWorkbook..ctor(String file) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook.cs:line 615
at ClosedXML_Sandbox.Program.Main(String[] args) in d:\Temp\closedxml-80652\ClosedXML\ClosedXML\ClosedXML_Sandbox\Program.cs:line 15
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

The error is located in this piece of code which handles comments:
var xml = xdoc.Root.Element("xml");
                        XElement shape;
                        if (xml != null)
                            shape = xml.Elements().First(e => (string)e.Attribute("type") == "#_x0000_t202");
                        else
                            shape = xdoc.Root.Elements().First(e => (string)e.Attribute("type") == "#_x0000_t202");
Somehow in our excel sheet, the comment has shape type #_x0000_t75. Which is also defined in the xdoc.

I quick fixed it for our situation by using FirstOrDefault and then checking if shape == null before continuing. But I think this could be handled more elegantly (since with my solution editing of the comment is not possible anymore).

file attachments

Closed Jul 26 at 7:58 PM by MDeLeon
fixed