Search code examples
c#excel-dna

ExcelDNA Parameter and Return Type Auto-conversion


I'd like to automatically try to convert input parameters from Excel-friendly types to ones that are useful in my AddIn and vice-versa back to Excel with the return values. For example, I'd like to define a an Excel function (as a C# method) like:

public static Vector<double> MyFunction(Vector<double> inputVector)
{
    // do some stuff to inputVector
    return inputVector
}

I'd like for it to convert my input params and return value 'behind the scenes', i.e. I define some generic conversion method for converting from object to Vector<double> and vice versa, and this is called before they are passed in/out of my defined method.

Is this possible? I found ParameterConversionConfiguration in the github repo but I'm not quite sure how to use it. Are there any examples or further documentation available? I can see that I might need to register my type conversions somehow, but I'm not sure how to proceed.

EDIT: After some more playing around, I did this to convert a return value from a Matrix to an array:

public class ExcellAddIn : IExcelAddIn
{
    public void AutoOpen()
    {
        var conversionConfig = GetParameterConversionConfig();
    }

    static ParameterConversionConfiguration GetParameterConversionConfig()
    {
        var paramConversionConfig = new ParameterConversionConfiguration()
            .AddReturnConversion((Matrix<double> value) => value.ToArray());
        return paramConversionConfig;
    }
}

But upon loading the .xll, Excel spits out an 'unsupported signature' error. Am I on the right track? What else do I need to do?


Solution

  • There's a complete sample add-in that uses these Excel-DNA Registration extensions here: https://github.com/Excel-DNA/Registration/tree/master/Source/Samples/Registration.Sample

    Some details relevant to your question:

    • You actually need to get the function registrations, apply your conversion and the perform the registration in your AutoOpen:

      public void AutoOpen()
      {
          var conversionConfig = GetParameterConversionConfig();
          ExcelRegistration.GetExcelFunctions()
                           .ProcessParameterConversions(conversionConfig)
                           .RegisterFunctions();
      }
      
    • You might want to suppress the default processing by adding an ExplicitRegistration='true' attribute in your .dna file: <DnaLibrary Name="My Add-In" RuntimeVersion="v4.0" > <ExternalLibrary Path="XXX.dll" ExplicitRegistration="true" .... /> </DnaLibrary>