使用C#从打开的Excel工作表中获取当前单元格值

问题描述 投票:0回答:1

我有一个打开的Excel实例已经通过COM进程连接到它,我已更改其中一个单元格的值。在C#中,我无法与工作表建立连接,但在python中,我可以

有效的Python代码:

import xlwings as xw
wb = xw.Book('c:/users/me/Desktop/mysheet.xlsx')
sheet = wb.sheets['Sheet1']
print(sheet.range('B1').value) # returns the current value

非工作C#代码:

var xlApp = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Workbook wb = xlApp.ActiveWorkbook; // returns null
Worksheet excelSheet = wb.ActiveSheet;
string test = excelSheet.Cells[1, 2].Value.ToString(); 

考虑到已经通过另一软件产品的COM自动化打开了它,是否有办法使C#连接到此表?

关于GetActiveObject的大多数在线讨论是与Excel的特定实例通信,如果有多个实例正在运行,而我遇到相反的问题,则是Excel的单个实例和试图连接到它的多个应用程序。

c# excel-interop
1个回答
0
投票
Workbook wb = System.Runtime.InteropServices.Marshal.BindToMoniker(@"c:\users\me\Desktop\mysheet.xlsx") as Workbook;

即使工作簿已经在Excel中打开,也应该得到它。

https://blogs.msdn.microsoft.com/eric_carter/2009/03/12/attaching-to-an-already-running-office-application-from-your-application-using-getactiveobject-or-bindtomoniker/

© www.soinside.com 2019 - 2024. All rights reserved.