C#导出Excel时遭遇0x80029C4A错误的解决方法
问题:Office Interop Excel 类型转换异常(TYPE_E_CANTLOADLIBRARY)
环境信息
- Visual Studio 2022 Community版本
- 已安装Microsoft Office 2013
- 引用的
Microsoft.Office.Interop.Excel库版本为15.0.0.0,运行时版本v2.0.50727
测试代码
using Excel = Microsoft.Office.Interop.Excel; // [...] private void exportExcel() { Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Add(); Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; string[,] data = { {"Nome", "Cognome", "Età"}, {"Mario", "Rossi", "30"}, {"Luigi", "Verdi", "25"}, {"Paola", "Bianchi", "28"} }; for (int i = 0; i < data.GetLength(0); i++) { for (int j = 0; j < data.GetLength(1); j++) { worksheet.Cells[i + 1, j + 1] = data[i, j]; } } string path = System.Reflection.Assembly.GetEntryAssembly().Location; path = path.Substring(0, path.LastIndexOf("\\")); path += "\\data.xlsx"; workbook.SaveAs(path); workbook.Close(); excelApp.Quit(); }
错误信息
执行Excel.Workbook workbook = excelApp.Workbooks.Add();时抛出异常:
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)).'
解决方案
修复Office安装
打开控制面板→程序和功能,找到Microsoft Office 2013,右键选择「更改」,选择「快速修复」或「联机修复」,完成后重启电脑。该操作可修复损坏的类型库或COM注册信息。重新注册Excel COM组件
以管理员身份启动命令提示符,根据Office位数执行对应命令:- 32位Office(无论系统位数):
cd "C:\Program Files (x86)\Microsoft Office\Office15" regsvr32.exe excel.exe - 64位Office:
cd "C:\Program Files\Microsoft Office\Office15" regsvr32.exe excel.exe
执行成功后会弹出注册提示,再重新运行程序。
- 32位Office(无论系统位数):
确保Interop库版本与Office匹配
右键项目→管理NuGet程序包,卸载现有Microsoft.Office.Interop.Excel,安装对应Office 2013的15.x.x版本,避免版本不兼容。调整项目平台目标
右键项目→属性→生成,将「平台目标」设置为与Office位数一致(Office 32位设为x86,64位设为x64),解决位数不匹配导致的COM转换问题。清理并重新生成项目
执行「生成→清理解决方案」,再执行「生成→重新生成解决方案」,清除编译缓存可能引发的异常。
内容的提问来源于stack exchange,提问作者Attilaa
相关产品推荐
相关产品推荐

