.NET Core 8.0中Microsoft.Office.Interop.Excel适配Excel 2016失败问题
问题描述
环境:Visual Studio 2022 + Microsoft Office 2016
操作步骤:
- 控制台项目中安装了Microsoft.Office.Interop.Excel NuGet包
- 手动添加了Microsoft.Excel 16.0 Object Library引用
- 类中添加
using Excel = Microsoft.Office.Interop.Excel;语句
现象:编译无报错,运行时触发中断模式,抛出错误:
System.IO.FileNotFoundException: 'Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. The system cannot find the file specified.'
程序代码:
using Microsoft.Office.Interop.Excel; class ExcelInteropExample { static void Main() { // 创建Excel应用实例 Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"]; worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet; worksheet.Name = "Exported from DataTable"; // 创建并填充测试用DataTable System.Data.DataTable Dt = new System.Data.DataTable(); Dt.Columns.Add("Column1", typeof(string)); Dt.Columns.Add("Column2", typeof(int)); // 添加测试数据 Dt.Rows.Add("Data1", 1); Dt.Rows.Add("Data2", 2); // 将DataTable数据写入Excel工作表 for (int i = 0; i < Dt.Rows.Count; i++) { for (int j = 0; j < Dt.Columns.Count; j++) { worksheet.Cells[i + 1, j + 1] = Dt.Rows[i][j].ToString(); } } // 保存工作簿 workbook.SaveAs("C:\\Users\\lenovo\\Downloads\\ExcelInteropExample.xlsx", XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } }
解决方案
- 清理重复引用:同时安装NuGet包和手动添加COM引用会导致版本冲突。直接移除项目中手动添加的
Microsoft.Excel 16.0 Object Library引用,仅保留NuGet安装的Microsoft.Office.Interop.Excel包即可。 - 补全Office组件:确保Office 2016是完整安装状态,尤其是Office共享组件。若存在缺失,可通过Office安装程序选择修复,或重新安装时勾选“Office共享功能”下的所有相关选项。
- 添加版本绑定重定向:在项目的
App.config文件中加入以下配置,让程序自动适配已安装的Office组件版本:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="office" publicKeyToken="71e9bce111e9429c" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-16.0.0.0" newVersion="16.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
- 对齐目标平台:Office 2016分32位和64位版本,需确保项目的目标平台(x86/x64/Any CPU)与Office安装版本一致。在Visual Studio中右键项目→属性→生成→目标平台,选择对应架构即可。
- 释放Excel进程资源:当前代码未释放Excel资源,虽不是本次报错的直接原因,但会导致进程残留占用内存,建议在代码末尾添加以下释放逻辑:
// 释放Excel资源 workbook.Close(false); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(app); worksheet = null; workbook = null; app = null; GC.Collect(); GC.WaitForPendingFinalizers();
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

