C# code to modify opened excel file?

Hello
I use Python to change excel values in realtime but from Grasshopper and Hops is running slowly.
Is there a similar code with C# ?

Interesting!
I didn’t know it could be so exposed!
I manually referenced a .dll library from
C:\Program Files (x86)\Microsoft Office\root\Office16\ADDINS\Microsoft Power Query for Excel Integrated\bin\Microsoft.Office.Interop.Excel.dll

Then something as compact as this already worked:

using Microsoft.Office.Interop.Excel;
private void RunScript(int row, int column, string val)
  {
    Microsoft.Office.Interop.Excel.Application myExcel;
    myExcel = ( Microsoft.Office.Interop.Excel.Application ) System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    myExcel.Cells[row, column] = val;
  }

edit excel from c#
edit excel from c# V0.1.gh (7.4 KB)


Edit
To “read” cells something like this can be used:
string str = ((Microsoft.Office.Interop.Excel.Range) myExcel.Cells[3, 1]).Value.ToString();

2 Likes

Thank you Riccardo , i will try it and compare it with python code.
Hops is useful but need to run the server every time outside Grasshopper.
There is also a useful python module but don’t edit opened excel file

I don’t know how to use C#, this is an equivalent with Python.
I tried it before but the problem that Microsoft office still exist in Processes even the excel file closed and the script don’t recognized the active document

import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
from System.Runtime.InteropServices import Marshal
excel = Marshal.GetActiveObject("Excel.Application")

workbook = excel.ActiveWorkbook
worksheet = excel.ActiveSheet

for i in range(4):
    print i
    excel.Cells[4+i, 3] = val[i]

How is it not recognizing it? I see it is working in the video…

Sorry I’ve never done such thing, that code of mine was just something clashed together in 5 min…

Excel app starts when the code start, if excel still runing from previous files the new file don’t working.
In the video i end task of Excel from previous files

You mean you have multiple excel files open and you want to target one in specific? By path+filename?
Or you want GH to open excel and start working with it?

Please be specific…

I would use code from here:

Work with target excel file is different and easy.
I already talked about opened excel file, i also talked about the problem and how i solved it