是否可以通过模拟在C#中打开excel互操作。我想打开excel应用程序,在C#程序运行的帐户以外的其他帐户下运行。默认情况下,它在运行C#程序的同一用户帐户下打开。
MyApp = new Excel.Application();
MyApp.Visible = false;
MyApp.DisplayAlerts = false;
MyBook = MyApp.Workbooks.Open(@"C:\Sample.xlsx");
任何其他方式也欢迎。
答案 0 :(得分:1)
为了从后面的代码中获取模拟上下文,您可以使用advapi32.dll
中的一些非托管函数。
LogonUser
以获取用户令牌WindowsIdentity
Impersonate
。这将返回WindowsImpersonationContext
,稍后可用于Undo
模拟ctx.Undo();
)并释放资源。多么糟糕,你不觉得吗?
幸运的是,你不必重新发明井。 Uwe Keim编写了一个类,在保持可重用性的同时完成了上述所有步骤
A small C# class for impersonating a user
using ( new Impersonator( "username", "domainName", "password" ) )
{
/* code that executes under the new context */
}