I am trying to build a generic method for exporting a list to excel. An object will have attributes if the property should be printed. ie:
public class someObject {
public int DontPrint {get; set;}
[ExcelAttributes(PrintMe = true)]
public int PrintMe {get; set;}
[ExcelAttributes(PrintMe = true)]
public int PrintMeToo {get; set;}
}
I need a generic way to examine a List and return a printable object. something like the following.
public AppendCell<T>(List<T> list)
var obj = list[0];
PropertyInfo[] propertyInfos;
propertyInfos = obj.GetType().GetProperties(BindingFlags.Public |
BindingFlags.Instance);
foreach (T list1 in list)
{
foreach (PropertyInfo info in propertyInfos)
{
object[] customAttr = info.GetCustomAttributes(true);
// create cell with data
foreach (object o in customAttr)
{
ExcelAttributes ea = o as ExcelAttributes;
if (ea != null && ea.PrintMe ==true)
Cell c = new Cell(info.GetValue(list1,null).ToString())
}
}
}
return c;
}
So...I basically want to be able to examine a list of objects, get the printable properties based on the value of an attribute and print the values for the printable property.
if we create a list of someObject with the values
{DontPrint = 0, PrintMe = 1, PrintMeToo = 2}
{DontPrint = 0, PrintMe = 4, PrintMeToo = 5}
{DontPrint = 0, PrintMe = 3, PrintMeToo = 8}
I would expect to see:
1 2
4 5
3 8
Code similar to what is posted does what I need. Is there a more concise way to get a list of the properties that have the PrintMe attribute, then iterate through the list and act upon those properties?