Skip to content
This repository has been archived by the owner on Mar 9, 2020. It is now read-only.

"An item with the same key has already been added" Exception when creating ExcelTable. #553

Open
Dude3030 opened this issue Sep 24, 2019 · 0 comments

Comments

@Dude3030
Copy link

If we have two equal cell values with illegal xml characters, <test> for example, and try to add
a table containing this cells:
var table = sheet.Tables.Add(sheet.Cells[sheet.Dimension.Address], "dataTable");
then we get the following exception:

ArgumentException: An item with the same key has already been added
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) in System.Collections.Generic.Dictionary'2.Insert(TKey key, TValue value, Boolean add) in OfficeOpenXml.Table.ExcelTable.GetStartXml(String name, Int32 tblId) in OfficeOpenXml.Table.ExcelTable..ctor(ExcelWorksheet sheet, ExcelAddressBase address, String name, Int32 tblId) в OfficeOpenXml.Table.ExcelTableCollection.Add(ExcelAddressBase Range, String Name) в Mfc.Web.Results.ExcelTableResult'1.CreatePackage() in D:\Agent_work\6\s\Mfc\Mfc.Web.Controllers\Results\ExcelTableResult{T}.cs:line 110

Looking at the source,

if (cell.Value == null || names.ContainsKey(cell.Value.ToString()))

the second part of the condition looks for cell value before xml encoding.
colName = SecurityElement.Escape(cell.Value.ToString());

Code above does not check encoded column value for presence in the dictionary.
So, for our example:

  1. String <test> does not exist in the names dictionary.
  2. After xml encoding we get the string &lt;test&gt; and add this value to the dictionary.
  3. In the next iteration we try to find the second string <test>, but this value do not exist in the dictionary.
  4. Therefore we try to add an item with the key &lt;test&gt; twice.
@Dude3030 Dude3030 changed the title "An item with the same key has already been added" Exception when cteating ExcelTable. "An item with the same key has already been added" Exception when creating ExcelTable. Sep 25, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant