Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to update the active sheet from the active Excel workbook using c#?

Tags:

c#

excel

vb6

I would like to update values in the current sheet in current document regardless of file name of excel.

In vb6.0 we could do

Set AppExcel = GetObject(, "Excel.Application")
Set SheetExcel = AppExcel.ActiveWorkbook.ActiveSheet

How ever I have been trying to do same in C# .

Is there a way to do same in C#.

like image 806
Thunder Avatar asked Dec 29 '22 07:12

Thunder


1 Answers

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Reflection;

public class MyClass
{
    public static void Main()
    {
        object xlApp  = Marshal.GetActiveObject("Excel.Application");
        Type t = xlApp.GetType();

        t.InvokeMember("Quit", BindingFlags.InvokeMethod, null, xlApp, null);

    }
}

I have modified the code based on the example given here.

Having said that, I think you could write code in vb.net (and use GetObject) and use the library from c#.

OR

You can refer the Microsoft.VisualBasic.dll.
And make a call to GetObject.

EDIT: Why should you need such a thing? Wouldn't creating an Excel Addin help?

If you have to write code in c# anyway, take care of releasing COM instances that you have created using Marshal.ReleaseComObject

EDIT2: In order to get the reference to ActiveSheet, you could write

object sheet = t.InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, xlApp, null);

Again, I suggest you not take this route.
Write code in VB6 to do what you need & call it from c#/vb.net.

like image 99
shahkalpesh Avatar answered Feb 03 '23 14:02

shahkalpesh