问题
My application just added a new function to allow export data into Excel. It worked fine on one device but when we implement it on the second one the following error appeared:
Error Message:
System.InvalidCastException: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' 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: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).
回答1:
The error may say it can't load a DLL but if you are trying to load Excel that is where the problem is. It can't find "EXCEL.EXE" using the registry.
For some people, doing a simple Office repair from Add\Remove programs: Modify is enough to fix the problem.
If you have already tried an Office repair then you can fix it manually by editing the registry.
Open Regedit as admin and go to:
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\
This is the location that shows where Excel is installed. At this point if you see multiple versions, "1.9", "1.8", "1.7" then you need to remove the extra entries. For example Excel 2019 is "1.9" so you would remove other versions no longer installed.
Once you have only one version you also need to check the bitness. I had moved from 32-bit to 64-bit but both keys were still present
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\1.9\0\Win32
Computer\HKEY_CLASSES_ROOT\TypeLib\{00020813-0000-0000-C000-000000000046}\1.9\0\Win64
I removed the Win32 key and everything began working again. Inside these keys the default value shows the full path to "EXCEL.EXE". Ensure that path is correct.
来源:https://stackoverflow.com/questions/50724520/unable-to-cast-com-object-excel