0

I have linked an application that gets data from an API, I open the sheet when a new contract is loaded to the program. Now I am trying to write new data to the excel sheet later in the program when i collect new data.

I know how to write data to the excel sheet and how to open the sheet I want to write on. The problem is I don't know how to write to the sheet once its already open, all I can get it to do is open another instance of the sheet.

I need to be able to open the sheet in one void and then update the now open sheet in a later void. How do I check to see if the sheet is open and if it is then access it again to write more data to it?

Here is how I have opened Excel,

Microsoft.Office.Interop.Excel.Application xlApp = new  Microsoft.Office.Interop.Excel.Application();
Console.WriteLine("Opening Excel...");

if (xlApp == null)
{
 Console.WriteLine("EXCEL could not be started. Check that your office installation and project references are correct.");
return;
}


xlApp.Visible = true;

Workbook wb = xlApp.Workbooks.Open(@"C:\Users\Craig Key\Desktop\AppExports\TestExport.xlsx");
Console.WriteLine("Opening Currently Linked Workbook...");

Worksheet ws = (Worksheet)wb.ActiveSheet;
Console.WriteLine("Opening Active Worksheet...");

if (ws == null)
{
Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct.");
}

Now later I need to find xlApp later in the program and write to it again, without opening another instance of the file.

dvjanm
  • 2,351
  • 1
  • 28
  • 42
Craig Key
  • 141
  • 4
  • 17
  • Related? http://stackoverflow.com/questions/6682678/accessing-an-open-excel-workbook-in-c-sharp – grek40 Feb 13 '17 at 16:19
  • Why not pass your `xlApp` as an argument into both methods (I assume that by void you mean a method with no return value) – pquest Feb 13 '17 at 16:19

1 Answers1

0

I figured this out after searching for a while, I needed to use the marsh to try to bind the the open instance and then work with it.

Microsoft.Office.Interop.Excel.Application xlApp = null;
//Microsoft.Office.Interop.Excel.Workbooks wbs = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
bool wasFoundRunning = false;
Microsoft.Office.Interop.Excel.Application tApp = null;
 //Checks to see if excel is opened
Console.WriteLine("CDC is looking for Excel...");
   try
   {
    tApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    wasFoundRunning = true;
   }
    catch (Exception)//Excel not open
   {
    wasFoundRunning = false;
   }
   if (true == wasFoundRunning)
   {
    //Control Excel
   }
Craig Key
  • 141
  • 4
  • 17