Question

I have to export data to Excel programmatically. I have a class with several properties. I was wondering if it's possible to retrieve values of all properties using a loop. For instance:

public class SqueezeProperties
{
    public int WidthField { get; set; }
    public string Width_unit { get; set; }
    public int ResPressure { get; set; }
    public int DensityField { get; set; }
    ......
 }

While writing to excel, I code as:

 t = typeof(SqueezeProperties);
 foreach (PropertyInfo field in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                oSheet.Cells[r, c++] = field.Name;

Now to input values, is there any way that I can iterate and find values of all properties that can be accessed, and store them in excel?

I doubt if it is even possible. I just taught myself how to access the property name & its details, so I thought maybe the other thing could also be possible and I am simply unaware of it.

Thanks

Was it helpful?

Solution

You can use PropertyInfo.GetValue.

(However according to specification the order of your properties is not guaranteed to be the same as the definition order. So to be safe you might want to order them.)


Also instead of getting them via reflection you could create a collection manually instead, this would take care of the order already.

e.g.

var properties = new Expression<Func<SqueezeProperties, object>>[]
{
    o => o.WidthField,
    o => o.Width_unit,
    //...
};
foreach (var exp in properties)
{
    var mem = (MemberExpression)exp.Body;
    var prop = (PropertyInfo)mem.Member;

    oSheet.Cells[r, c++] = prop.GetValue(squeezePropertiesInstance, null);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top