我已经链接了一个从API获取数据的应用程序,我在将新合同加载到程序时打开工作表。现在,当我收集新数据时,我正试图在程序的后期将新数据写入Excel工作表。
我知道如何将数据写入Excel工作表以及如何打开我要写的工作表。问题是我不知道如何在已经打开的情况下写入工作表,我可以让它做的就是打开工作表的另一个实例。
我需要能够在一个空格中打开工作表,然后在稍后的空白中更新现在打开的工作表。如何检查工作表是否打开以及是否再次访问以向其写入更多数据?
以下是我打开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.");
}
现在稍后我需要在程序中稍后找到xlApp
并再次写入,而不打开该文件的另一个实例。
答案 0 :(得分:0)
我在搜索了一段时间之后想出了这个,我需要使用沼泽来尝试绑定打开的实例然后使用它。
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
}