在C#中使用模拟打开excel互操作

时间:2015-04-15 10:03:39

标签: c# excel excel-interop

是否可以通过模拟在C#中打开excel互操作。我想打开excel应用程序,在C#程序运行的帐户以外的其他帐户下运行。默认情况下,它在运行C#程序的同一用户帐户下打开。

        MyApp = new Excel.Application();
        MyApp.Visible = false;
        MyApp.DisplayAlerts = false;
        MyBook = MyApp.Workbooks.Open(@"C:\Sample.xlsx");

任何其他方式也欢迎。

1 个答案:

答案 0 :(得分:1)

为了从后面的代码中获取模拟上下文,您可以使用advapi32.dll中的一些非托管函数。

  • 致电LogonUser以获取用户令牌
  • 根据用户令牌
  • 创建WindowsIdentity
  • 在Windows标识上调用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 */
}