【问题标题】:change excel password using c#?使用c#更改excel密码?
【发布时间】:2011-11-04 19:49:43
【问题描述】:

我正在做这个项目,它使用 Excel.interop 创建工作表,目前它们受密码保护。使用 c# 修改密码的最佳方法是什么?我是互操作新手,所以不熟悉所有可用功能。

目前我使用 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 块来实现业务逻辑。有没有更好的方法来解决这个问题?

也许我可以从 catch 块内部返回 0 来调用方法,然后使用新密码调用不同的方法来取消保护工作表。但这将是代码复制。任何专业知识???

【问题讨论】:

  • 为什么不在创建工作表的同一操作中更改密码?在那之后,您可以依赖使用新密码。
  • 我不知道该怎么做。您能否显示示例代码或其他内容。
  • 您说您的应用程序创建了工作表:这是您的代码,所以大概您已经知道如何创建这些工作表了?
  • 这不是我的代码,我刚开始在这家公司工作,代码的所有者去世了。你指的是这条线吗? Excel.Worksheet wsheet = (Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[Name];
  • 如果您对代码不太熟悉,并且您的 try-catch 正在工作(即使不理想),那么我现在不会担心。也许在您花更多时间使用该应用程序并更好地了解它们如何组合在一起后重新访问。

标签: c# excel c#-4.0 interop password-protection


【解决方案1】:

免责声明:我不进行 Office 互操作编程。话虽如此,我还做了很多其他编程,所以也许这会是有用的建议。

首先,我在上面的 cmets 中向 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...]
  }
}

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2014-12-10
    • 2018-09-08
    • 2021-02-12
    相关资源
    最近更新 更多