Reading excel file throws a COMException

0

I am trying to read from an EXCEL file and display what i get.

Here is my Excel Class.

class Excel
    {
        private string path = "";
        _Application excel = new _Excel.Application();
         Workbook workbook;
         Worksheet worksheet;

        public Excel(string path, int sheet)
        {
            this.path = path;
            workbook = excel.Workbooks.Open(path);
            worksheet = workbook.Worksheets[sheet];
        }

        public string ReadCell(int row, int column)
        {
            row++;
            column++;

            if (worksheet.Cells[row, column].Value2 != null)
            {
                return worksheet.Cells[row, column].Value2;
            }
            else
            {
                return "";
            }
        }
    }

Here is how i call it

string pathToFile = @"K:\hours\tracking.xlsx";
Excel excel = new Excel(pathToFile, 1);
MessageBox.Show(excel.ReadCell(0, 0));

Here is my exception

System.Runtime.InteropServices.COMException HResult=0x80040154 Message=Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)). Source=mscorlib StackTrace: at System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType) at System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType) at System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj) at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Activator.CreateInstance(Type type) at working_hours.Excel..ctor(String path, Int32 sheet) in K:\programming\visual_studio_projects\working_hours\working_hours\working_hours\Excel.cs:line 14 at working_hours.Program.Main(String[] args) in K:\programming\visual_studio_projects\working_hours\working_hours\working_hours\Program.cs:line 31

I Chcked if the path is correct and it is.

I think it may have to do with the References that i just implemented, but im not quite Sure.

I added

System.Windows.Forms.dll and Microsoft.Office.Interop.Excel.dll

If anyone has any idea please let me know.

Thank you.

c#
excel
file
interop
asked on Stack Overflow Apr 24, 2019 by learningsymfony

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0