Cannot create an instance of Excel 2016 in Visual Studio 2015

3

I have Visual Studio 2015 and my application is for .NET Framework 4.0.

I installed Microsoft Office Home&Buissness 2016 and trying tocreate an instance using this code: Microsoft.Office.Interop.Excel.Application excelAppTemplate = new Microsoft.Office.Interop.Excel.Application();

but I get this error:

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}' failed due to the following error: Interface not registered (Exception from HRESULT: 0x80040155).

I am referencing Microsoft.Office.Interop.Excel 15.0.0.0. While searching for answers, I have seen a solution to delete this registry key:

HKEY_CLASSES_ROOT\TypeLib{00020813-0000-0000-C000-000000000046}

But I have 1.9 and not the previous version like 1.8 or 1.7, just 1.9. Is there any new version for Office 2016?

c#
asked on Stack Overflow Mar 29, 2016 by Liran Kremer • edited Mar 29, 2016 by Alexey Zimarev

1 Answer

-1

Instead of Microsoft.Office.Interop.Excel.Application library i recommend you to use more lithely configurable and stable library EPPlus. It works much times faster than reflection-based COM hell-library, and it can be installed through nuget.

Had to mention, that EPPlus supports only xlsx file format, and if you need to work with older xls-file formats, you can use library CSharpJExcel, that works without COM, for reading your xls files and then save them as xlsx through EPPlus.

Such convertion from xls to xlsx can looks like:

// Reading xls-file data with CSharpJExcel

var cellsData = new List<List<string>>();

var book = Workbook.getWorkbook(new FileInfo(fileName));
var dataSheet = book.getSheet(0);

// Loop over rows and fill collection with data
for (int r = 0; r < dataSheet.getRows(); r++)
{
    var dataRow = new List<string>();

    // Loop over columns  
    for (int c = 0; c < dataSheet.getColumns(); c++)
    {
        var cellValue = dataSheet.getCell(c, r).getContents();
        dataRow.Add(cellValue);
    }

    cellsData.Add(dataRow);
}


// Saving data to xlsx file with EPPlus
using (var xls = new ExcelPackage(new FileInfo(path + ".xlsx")))
{
    var sheet = xls.Workbook.Worksheets.Add("test");

    int row = 1;
    foreach (var cellsRow in cellsData)
    {
        int col = 1;

        // Some data processing logic...

        foreach (var cellData in cellsRow)
        {
            sheet.Cells[row, col].Value = cellData;

            ++col;
        }
        ++row;
    }

    xls.Save();
}
answered on Stack Overflow Mar 29, 2016 by Fragment • edited Mar 29, 2016 by Fragment

User contributions licensed under CC BY-SA 3.0