Search code examples
c#.netexcelexport-to-exceloffice-interop

Values storable in Excel


Good evening!

Which types of values can be directly stored into an Excel worksheet using Range.Value2 and how do I quickly check if a particular value can?

Suppose I have an array of objects, perhaps multityped (e.g. one int, one double and one Foo stored in an object[]).

If I shall choose a range of width 3 and try to store this array using Range.Value2, this will result in an exception (of course Excel doesn't know what is a Foo).

I came up with an idea of checking each value in the array, and, if it's not storable, convert it to its string representation using ToString(). But how do I check if it's initially storable?

It would be horrible to end up doing something like that:

public bool storable<T>(T value)
{
     return value is int  ||
            value is uint ||
            value is short ||
            value is byte ||
            ...
            value is string;
}

...especially knowing that each is will cast the variable to the tested type and seriously affect performance.

On the other hand, I can't afford pre-casting each value to the string type as I sometimes want to be able to do graphs and diagrams with numeric values, not strings.

Can you tell me I am mistaken or offer me any solution to the problem? Thank you!


Solution

  • I think you're going to have to do what you're unkeen to do (all the "is" checks), unless you can somehow make your input array a bit more strongly typed. Your best bet might be just to order the casts such that the most common ones get hit first.