J'ai un projet qui crée des fichiers Excel et j'aimerais ajouter quelques fonctionnalités d'importation. En un mot, je voudrais donner aux utilisateurs la possibilité de coder les éléments suivants:Comment importer/analyser des données de collection?
worksheet.Cell(1, 1).Value = collectionObject;
(où collectionObject implémente IEnumerable)
Comment puis-je analyser un IEnumerable de tout type et extraire les valeurs de les propriétés et les champs de chaque élément?
Ceci est ma tentative a échoué:
class Program
{
static void Main(string[] args)
{
// It fails with a list of strings
var listOfStrings = new List<String>();
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<Person>();
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++;
}
}
}
}
Lorsque vous dites "échoué" - que se passe-t-il? –
J'ai modifié l'exemple un peu pour le rendre plus clair, il fonctionne avec une liste d'objets POCO mais il échoue avec une liste de chaînes de caractères Comment puis-je le faire fonctionner avec un liste de String, Int32, etc? – Manuel