在C#中访问一个开放的Excel工作簿 [英] Accessing an open Excel Workbook in C#

查看:423
本文介绍了在C#中访问一个开放的Excel工作簿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问一个excel文件已经打开。我以为只是检查 .Workbooks 属性,这将是有,但事实并非如此。什么是去打开的工作簿的引用的正确方法?

I need to access an excel file that is already open. I thought just inspecting the .Workbooks property that it would be there but it isn't. What is the right way to get a reference to the open workbook?

var app = new Microsoft.Office.Interop.Excel.Application();

// the count is 0 =(
app.Workbooks.Count == 0;

修改

我可以通过...

app = (Excel.Application)Marshal.GetActiveObject("Excel.Application");

app.Workbooks.Count 还是 0 为什么是不是能够得到打开的工作簿引用?

but app.Workbooks.Count is still 0 why isn't it able to get a reference to the opened workbook?

推荐答案

而不是实例化一个新的实例,检查一个现有的:

Instead of instantiating a new instance, check for an existing one:

try
{
  Microsoft.Office.Interop.Excel.Application app = 
      System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch
{
  // Excel is not running.
}

这篇关于在C#中访问一个开放的Excel工作簿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆