Getting Errors with Excel Code

Experiences, small talk, and other automation gossip.
Posts: 8
Joined: Tue Aug 03, 2021 12:50 pm

Getting Errors with Excel Code

Post by navneet » Tue Dec 07, 2021 10:18 am

I am trying to convert text file into excel file and for this I am using Excel Interop. But it is throwing error.

Error message is as below:
Cannot find the interop type that matches the embedded interop type 'Microsoft.Office.Interop.Excel.WorkbookEvents_Event'. Are you missing an assembly reference? (CS1748)

As a workaround I tried to add Microsoft.Office.Interop.Excel; in the references by going to Projects ->Add reference but unfortunately could not find the Microsoft.Office.Interop.Excel option in GAC or COM . Please support

Assembly references used:
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Linq;

Code: -
string sourcefile;
string destfile;
sourcefile= @"C:\\Tempp\\Inputfile.txt;
[email protected]"C:\\Tempp\\output.csv";

int i, j;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel._Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
string[] lines, cells;
lines = File.ReadAllLines(sourcefile);
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlWorkBook = xlApp.Workbooks.Add();
xlWorkSheet = (Excel._Worksheet)xlWorkBook.ActiveSheet;
for (i = 0; i < lines.Length; i++)
cells = lines.Split(new Char[] { '\t', ';' });
for (j = 0; j < cells.Length; j++)
xlWorkSheet.Cells[i + 1, j + 1] = cells[j];
xlWorkBook.SaveAs(destfile, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);

Posts: 9
Joined: Fri May 28, 2021 3:51 pm

Re: Getting Errors with Excel Code

Post by JasonY » Fri Dec 10, 2021 11:14 pm

Hello Navneet,

You can add the reference to "Microsoft.Office.Interop.Excel" using the built-in Nuget library we have:

1. In the Projects panel
2. Right-click on References
3. Select Manage Packages...
4. Search for Microsoft.Office.Interop.Excel in the search bar
5. Click Add

That will add a reference to what you are looking for.