2011-11-04 35 views
0

我正在使用Excel.interop创建工作表的这个项目,目前他们是密码protected.Whats最好的方式来修改密码使用C#?我是互操作新手,所以不熟悉所有可用的功能。使用c#更改excel密码?

当前我使用worksheet.unprotect(oldpassword)来使用旧密码解锁工作表,然后使用新密码调用worksheet.protect(newpassword)将其锁定。但是随后出现此问题。它第一次正常工作,但之后当它试图使用oldpw解除保护时,我得到异常。所以旧的pw是1次使用,我如何在c#中实现该逻辑?另外,我有15个工作表(所有密码都受保护),因此在使用计数器时会变得复杂。

目前我使用这样的try catch块。

public static void Unprotect_Worksheet(string Name) 

     { 
      try 
      { 

       //try old pw first, if gets exception, retry using new pw 

       string strPassword = oldpassword; 
       Excel.Worksheet wsheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[Name]; 

       wsheet.Unprotect(oldpassword); 

      } 
      catch 
      { 

       string strPassword = newpassword; 
    Excel.Worksheet wsheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[Name]; 

       wsheet.Unprotect(strPassword); 


      } 
     } 

这工作得很好,但我真的不认为一个catch块应该用于实现业务逻辑。有没有更好的方法来解决这个问题?

可能是我可以返回0从调用方法从内部catch块,然后调用不同的方法来取消保护工作表使用新密码。但那会是代码复制。任何专长?

+0

为什么不直接在创建表(或多个)相同的操作更改密码?在那之后,您可以依靠使用新密码。 –

+0

我不知道该怎么做。你可以请示例代码或其他东西。 –

+0

你说你的应用程序创建了工作表:它是你的代码,所以你可能已经知道你是如何创建这些工作表的? –

回答

0

声明:我不会做Office interop编程。这就是说,我做了很多其他的编程,所以也许这将是有益的建议。

首先,我会在上面的评论中给Tim Williams提供道具,建议您稍后在熟悉代码后重新访问它。直到你花了一些时间用现有的代码,重写逻辑是不明智的。

现在:如果调用Worksheet.Unprotect(这是一个COM接口)产生时指定了错误的密码例外,那么你将不得不尝试/捕获异常。这似乎是处理错误的唯一方法。所以,要回答你的一个问题,你需要try/catch块。

给你提供的代码,我可能会像这样重新工作吧:

string strPassword = oldpassword; 
Excel.Worksheet wsheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[Name]; 

try { 
    // try the old password first (throws a COM exception if it fails) 
    wsheet.Unprotect(oldpassword); 
} catch { 
    // ideally we should make sure we're only handling an invalid password error here 
    try { 
    // couldn't unprotect with the old password - try the new password 
    strPassword = newpassword; 
    wsheet.Unprotect(strPassword); 
    } catch(Exception ex) { 
    // TODO neither password worked - what do we do now? [insert code here...] 
    } 
}