I try to read my Exel file from code and received System.InvalidCastException:
Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Tools.Excel.Worksheet'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{297DC8D9-EABD-45A1-BDEF-68AB67E5C3C3}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
This error occurs in objsheet = appExcel.ActiveWorkbook.ActiveSheet; so I try to cast it into objsheet = (Worksheet)appExcel.ActiveWorkbook.ActiveSheet; but this error still exist
using Microsoft.Office.Interop.Excel;
private static Microsoft.Office.Interop.Excel._Application appExcel;
private static Microsoft.Office.Interop.Excel.Workbook newWorkbook = null;
private static Microsoft.Office.Interop.Excel.Worksheet objsheet = null;
private static string file = @"D:\file.xlsx";
//Method to initialize opening Excel
static void excel_init(String path)
{
//appExcel = new Microsoft.Office.Interop.Excel.Application();
if (System.IO.File.Exists(path))
{
// then go and load this into excel
newWorkbook = appExcel.Workbooks.Open(file, true, true);
int count = newWorkbook.Worksheets.Count;
if (count > 0)
{
objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook.Worksheets[1];
}
}
else
{
MessageBox.Show("Unable to open file!");
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
System.Windows.Forms.Application.Exit();
}
}
newWorkbook is null.