Pregunta

I am coding C# (Visual Studio Express 2012) and using ExcelIntegration. I want to let an ExcelFunction return a user defined object to a cell. And I further want an ExcelFunction take a userdefined object as input.

Here is an example of my code. This does not work, neither of the functions (CreateDog or GetName) are visible from Excel.

namespace Test
{
    public class Dog
    {
        public Dog(string name)
        {
            Name = name;
        }

        public readonly string Name;
    }

    public class TestClass
    {
        [ExcelFunction]
        public static Dog CreateDog(string name)
        {
            return new Dog(name);
        }

        [ExcelFunction]
        public static string GetName(Dog dog)
        {
            return dog.Name;
        }
    }
}

After Answer from yesterday I added a Dictionary. I have modified the code as below. This works. My question now is how to make this generic. Can I modify the ExcelDNA code somehow to do this dictionary stuff automatically for me?

namespace ExcelIntegration { public class Dog { public Dog(string name) { Name = name; }

    public readonly string Name;
}

public class TestClass
{
    static Dictionary<string, Dog> DogStore;

    [ExcelFunction]
    public static string CreateDog(string name)
    {
        Dog dog = new Dog(name);
        string key = dog.ToString() + "_" + DateTime.Now.Ticks.ToString();
        try
        {
            if (DogStore.ContainsKey(key) == false) DogStore.Add(key, dog);
        }
        catch (NullReferenceException)
        {
            DogStore = new Dictionary<string, Dog>();
            if (DogStore.ContainsKey(key) == false) DogStore.Add(key, dog);
        }
        return key;
    }

    [ExcelFunction]
    public static string GetName(string dogKey)
    {
        Dog dog = DogStore[dogKey];
        return dog.Name;
    }

}

}

¿Fue útil?

Solución

Excel-DNA does not yet have this kind of custom marshaling or object support built in. Depending on what you need, it might be as simple as adding some wrappers and conversion functions and an object dictionary to your code, or you might need to generate all the wrappers dynamically and register the new functions at runtime.

Cubicle Tools is a recent (open-source) project that adds an extensive distributed object and code model on top of Excel-DNA. But that's a fairly complicated project to get your head around.

There's a very simple F#-based implementation of an object handler on top of the RTD mechanism described in this thread. (But that code can be made much nicer with the current Excel-DNA version.)

If you're just looking for some guidance, and your 'Dogs' are not too finicky, then the Excel-DNA Google group is probably the best place for a discussion.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top