“Old format or invalid type library” error while working with excel

This error is a bug. See BUG: “Old format or invalid type library” error when automating Excel.
There are 3 workarounds i choose for this one:
set the CultureInfo prior to calling the Excel method. For example:

Dim oApp As New Excel.Application()
oApp.Visible = True
oApp.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
                            System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
                                  New System.Globalization.CultureInfo("en-US")
oApp.Workbooks.Add()
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI

But still the errors came. Finally i found this page Excel Automation: the CultureInfo bug, it told me why there still where errors
If you’re doing some Excel automation like creating a sheet with some graphs from .NET, you may run into the “Old format or invalid type library” error which is quite nicely described in this Microsoft Support article. At this moment there’s no fix available, but the article describes not one, not two, but three workarounds. I chose the third one where you switch the Culture for your thread to “en-US”.

When giving this a try, it solved the error mentioned above but then I started getting “Exception from HRESULT: 0x800A03EC” errors. After searching for a while I finally found the reason: you should not switch the Culture back to the original one after you’ve added your new Excel workbook as shown in the workaround. First finish whatever you want to automate in Excel and switch the Culture back at the end.

In C# this looks like the following:

// code below assumes the following using statement
// using Excel = Microsoft.Office.Interop.Excel;

// capture current Culture settings
System.Globalization.CultureInfo systemCultureInfo =
                           System.Threading.Thread.CurrentThread.CurrentCulture;

try
{
    // temporarily change CultureInfo to en-US
    System.Threading.Thread.CurrentThread.CurrentCulture =
                                  new System.Globalization.CultureInfo("en-US");

    Excel.Application excelApplication = new Excel.Application();

    // create new workbook
    Excel._Workbook workbook =
               (Excel._Workbook)(excelApplication.Workbooks.Add(Missing.Value));

    // get active sheet
    Excel._Worksheet worksheet = (Excel._Worksheet)workbook.ActiveSheet;

    // create your graphs or whatever you were planning to automate in Excel

    // give the user control over Excel
    excelApplication.Visible = true;
    excelApplication.UserControl = true;
}
catch (Exception ex)
{
    // handle exception
}
finally
{
    // put CultureInfo back to original
    System.Threading.Thread.CurrentThread.CurrentCulture = systemCultureInfo;
}

Leave a Reply