Search code examples
c#excel-dna

How do I create a new worksheet and populate it with rows of data using Excel-DNA?


I have c# code behind my Excel-dna addin which is successfully downloading data from a service. I have created a ribbon in Excel-dna with a button which triggers the download, and now I want to display the data in a new worksheet. How do I create a worksheet and add rows?

I tried calling xlcWorkbookInsert from my c# code using:

  ExcelReference newSheet = (ExcelReference)XlCall.Excel(XlCall.xlcWorkbookInsert, 1);

but I always get a ExcelDna.Integration.XlCallException exception. Is this the correct approach, or is there a simpler way to go about doing this?

I also tried pasting an object[,] of data to an existing sheet:

   ExcelReference sheet1 = (ExcelReference)XlCall.Excel(XlCall.xlSheetId, "Sheet1");

   ExcelReference myTargetPasteArea = new ExcelReference(1, 1, 2, 10, sheet1.SheetId);

   myTargetPasteArea.SetValue(result);

There are no errors this time, but nothing happens (although I can see the code being executed when I step through in debug).


Solution

  • Your code is calling to Excel via the C API (that's how the XlCall.Excel(...) and ExcelReference stuff in Excel-DNA works). But you can't call the C API directly from your ribbon event handler. You have two options:

    • Make a detour via a macro. This is easy if you change your ribbon xml code:

      <button onAction="RunTagMacro" tag="MyMacro" />

    and then define a macro:

    public static void MyMacro()
    {
        // ... do your work here ....
    }
    

    You can also call the macro yourself from the event handler - the RunTagMacro internally just calls

    object app = ExcelDnaUtil.Application;
    app.GetType().InvokeMember("Run", BindingFlags.InvokeMethod, 
        null, app, new object[] { control.Tag }, new CultureInfo(1033));
    
    • Another option is to change your interaction code to use the COM API. For this you'll need to use the 'dynamic' support in .NET 4, or reference an interop assembly - either the version-specific Primary Interop Assemblies for Office, or some version-independent interop assemblies like NetOffice.