Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to import/parse collection data?
    primarykey
    data
    text
    <p>I have a project that creates Excel files and I'd like to add some import functionality. In a nutshell I'd like to give users the ability to code the following:</p> <p><code>worksheet.Cell(1, 1).Value = collectionObject;</code></p> <p>(Where collectionObject implements IEnumerable)</p> <p>How can I parse an IEnumerable of any type and extract the values of each item's properties and fields?</p> <p>This is my failed attempt:</p> <pre><code>class Program { static void Main(string[] args) { // It fails with a list of strings var listOfStrings = new List&lt;String&gt;(); listOfStrings.Add("House"); listOfStrings.Add("Car"); new ParseCollections().ParseCollection(listOfStrings, 1, 1); // Get error "Parameter count mismatch." when calling info.GetValue(m, null).ToString() // The property is an array "Chars". // I tried filtering the property with "info as IEnumerable == null" but it doesn't catch it. // How can I filter collection properties here? // It works with a list of POCO var listOfPOCO = new List&lt;Person&gt;(); listOfPOCO.Add(new Person() { Name = "John", Age = 30 }); listOfPOCO.Add(new Person() { Name = "Jane", Age = 25 }); new ParseCollections().ParseCollection(listOfPOCO, 1, 1); } class Person { public String Name { get; set; } public Int32 Age { get; set; } } } class ParseCollections { public void ParseCollection(Object collectionObject, Int32 initialRow, Int32 initialColumn) { var asEnumerable = collectionObject as IEnumerable; if (asEnumerable != null) { var ro = initialRow; foreach (var m in asEnumerable) { var co = initialColumn; var fieldInfo = m.GetType().GetFields(); foreach (var info in fieldInfo) { Console.WriteLine("Cell({0}, {1}) = {2}", ro, co, info.GetValue(m).ToString()); co++; } var propertyInfo = m.GetType().GetProperties(); foreach (var info in propertyInfo) { Console.WriteLine("Cell({0}, {1}) = {2}", ro, co, info.GetValue(m, null).ToString()); co++; } ro++; } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload