【问题标题】:Find and edit open Excel sheet using interop使用互操作查找和编辑打开的 Excel 工作表
【发布时间】:2017-03-14 02:46:40
【问题描述】:

我已经链接了一个从 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 并再次写入它,而无需打开文件的另一个实例。

【问题讨论】:

标签: c# excel


【解决方案1】:

我找了一会儿才知道,我需要使用沼泽尝试绑定打开的实例,然后使用它。

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
   }

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多