In my console Application I want to use Microsoft.Office.Interop.Excel library. I use Visual Studio 2022 and Microsoft Office 2016. I added a reference Microsoft.Excel 16.0 Object Library and in my class I added using Excel = Microsoft.Office.Interop.Excel after installing Microsoft.Office.Interop.Excel nuget package; When I click build it doesn't shows any error and tells that Build Complete, but when I run my Application I'm getting this error in Break Mode
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.'
Here is what the program looks like
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);
}
}
There is no need to use any specific NuGet packages if you want to automate Office applications from any .Net 8 based application. All you need is to add a COM reference to the required type library:
Then add the required COM reference to the project:
As a result your project file should like in the following way for the console application: