Unable to pass COM object of type "Microsoft.Office.Interop.Excel.WorksheetClass"

I am trying to create and save a new excel document in C # from a collection of aggregate data. Right now, I'm just trying to get the basics to work before editing table cells, etc. Here I am just trying to set the content of one cell:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Office.Interop.Excel;

namespace DebugReport
{
    class MonumentDebugReport
    {
        static void Main(string[] args)
        {    
            Worksheet spreadsheet = new Worksheet();

            spreadsheet.Cells[0, 0] = "stuff";
       }
    }
}

      

This returns:

Unable to pass COM object of type 'Microsoft.Office.Interop.Excel.WorksheetClass' to interface type 'Microsoft.Office.Interop.Excel._Worksheet'. This operation failed because the call to the QueryInterface of the COM component for the interface with IID '{000208D8-0000-0000-C000-000000000046} failed with the following error: This interface is not supported (exception from HRESULT: 0x80004002 (E_NOINTERFACE)) ...

in the row where I am setting the cell. For me, this looks like most of the examples / tutorials I've seen, and I can't find anything in the C # documentation to indicate that this won't work.

+3


source to share


1 answer


As Hans already said, you first need to create an Excel application, then add a workbook to it, then add a worksheet (or try to access an existing one Sheets[1]

)

Give using Microsoft.Office.Interop.Excel

and pseudonym

using Excel = Microsoft.Office.Interop.Excel



and then

Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlWb = xlApp.Workbooks.Add() as Excel.Workbook;
Excel.Worksheet xlSheet = xlWb.Sheets[1] as Excel.Worksheet;
Excel.Range range = xlSheet.get_Range("A1");

range.Value = "hello world!";

      

and then see How to properly clean up Excel interaction objects

+6


source







All Articles