c# - Return type of Application.Evaluate in exotic cases -
i trying write method in c# will, given name of named range in excel workbook, retrieve values in range. i'd work if named range isn't pure reference range (e.g. =sheet1!a1:a10) instead ={1,2,3,4,5} or =offset(sheet1!a1:a10,3).
i'm doing following:
excel.application xl = ...; excel.name name = ...; object value = xl.evaluate(name.value); // if it's range, turn object[] or object[,] if (value excel.range) value = ((excel.range)value).value2; if (value object[]) { // stuff } else if (value object[,]) { // different stuff } i had thought named range value ={1,2,3,4,5} come out object[] or object[,], doesn't. value.gettype() reports system.__comobject (edit: i'm getting system.object[*], , haven't been able reproduce system.__comobject - still doesn't cast object[]), , haven't been able narrow down further.
what type should casting value to?
edit: here test code , output. may simpler question of "what heck system.object[*], vagaries of google don't permit me search for.
code:
using system; using excel = microsoft.office.interop.excel; namespace test { class program { static void main(string[] args) { excel.application xl = new excel.application(); object value = xl.evaluate("={1,2,3,4,5}"); console.writeline(value); console.writeline(value object[]); console.writeline(value.gettype()); console.readline(); xl.quit(); } } } output:
system.object[*]
false
system.object[*]
edit2: if instead evaluate "={1;2;3;4;5}" object[,]. huh.
i think it's because array created excel not 0-based, 1-based, can convert this:
object[] ints = ((array)value).toarray<object>(); with helper method extension:
public static t[] toarray<t>(this array array) { if (array == null) return null; if (array.rank != 1) throw new notsupportedexception(); var newarray = new t[array.getlength(0)]; var lb = array.getlowerbound(0); (int = 0; < newarray.length; i++) { newarray[i] = (t)array.getvalue(i + lb); } return newarray; } if use .net 4, there chances return type of evaluate defined dynamic. code:
dynamic value = xl.evaluate("={1,2,3,4,5}"); // or var instead of dynamic you system.invalidcastexception: unable cast object of type 'system.object[*]' type 'system.object[]' because new .net 4 interop layer try automatically create standard array. need instead (like in code):
object value = xl.evaluate("={1,2,3,4,5}"); object[] ints = ((array)value).toarray<object>();
Comments
Post a Comment