在我的控制台应用程序中,我想使用 Microsoft.Office.Interop.Excel 库。我使用 Visual Studio 2022 和 Microsoft Office 2016。我添加了一个参考 Microsoft.Excel 16.0 Object Library ,并在我的班级中安装了 Microsoft.Office.Interop.Excel nuget 包后使用 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()
{
// Create Excel application instance
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";
// Create and populate a System.Data.DataTable for testing
System.Data.DataTable Dt = new System.Data.DataTable();
Dt.Columns.Add("Column1", typeof(string));
Dt.Columns.Add("Column2", typeof(int));
// Add some sample data to the DataTable
Dt.Rows.Add("Data1", 1);
Dt.Rows.Add("Data2", 2);
// Write data from DataTable to Excel worksheet
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();
}
}
// Save the workbook
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);
}
}
如果您想从任何基于 .Net 8 的应用程序自动化 Office 应用程序,则无需使用任何特定的 NuGet 包。您所需要的只是添加对所需类型库的 COM 引用:
然后将所需的COM引用添加到项目中:
因此,对于控制台应用程序,您的项目文件应如下所示:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Interop.Excel">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>9</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>00020813-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
</Project>