【问题标题】:Worksheet.Unprotect - Office Interop - Difference between 2003 and 2007Worksheet.Unprotect - Office 互操作 - 2003 和 2007 之间的差异
【发布时间】:2011-01-24 04:47:17
【问题描述】:

我有一个 .NET winforms 应用程序,它可以自动执行 Excel 并检查工作表密码。要求是能够检测到 1) 保护被关闭 2)密码被删除(受保护但没有密码) 3) 密码与数据库中的正确密码匹配

为满足第二个要求,程序使用空字符串调用 Worksheet.Unprotect 命令,捕获错误。如果按预期出错,则进行第三次检查。如果没有错误,那么 Unprotect 在没有密码的情况下工作 ==> 密码已被删除。

下面的代码示例有这些检查。

该应用程序可以在 Office 2003 中很好地完成这项工作。我已经将我的开发计算机更新到了 Office 2007,但它不再像以前那样工作了。当我调用 Worksheet.Unprotect 时,Excel 会提示输入密码!

我需要知道应该如何在新版本的 Excel 中完成这项工作,或者是否有办法引用旧的 PIA。无论如何,如果我设置对 Excel 11 的引用,它将被 GAC 中的 12 的 PIA 替换。

'return true if unprotect of worksheet does not generate an error
    'all other errors will bubble up
    'return false if specific error is "Password is invalid..."
    Try
        'detect unprotected or no password
        If oWorksheet.ProtectContents Then
            'try with no passsword and expect an error
            'if no error then raise exception
            Dim blnRaiseException As Boolean = True
            Try
                'oWorksheet.Unprotect(vbNullString)
                oWorksheet.Unprotect()
            Catch ex As Exception
                blnRaiseException = False
            End Try

            If blnRaiseException Then
                Throw New ExcelSheetNoPasswordException
            End If

            oWorksheet.Unprotect(strPwd)
            'no error so if we get here -- success
            fnCheckWorksheetPwd = True

            'leave as it was -- this may still cause workbook to think it is changed
            oWorksheet.Protect(strPwd)
        Else
            Throw New ExcelSheetNotProtectedException
        End If

    Catch COMex As System.Runtime.InteropServices.COMException
        'handle error code -2146827284 
        If COMex.ErrorCode = -2146827284 Then
            'this is the error we're looking for
        Else
            Throw
        End If
    Catch ex As Exception
        Throw
    End Try

【问题讨论】:

  • 如果将 Excel.Application 实例的 DisplayAlerts 属性设置为 False,会发生什么情况?

标签: .net excel com interop ms-office


【解决方案1】:

使用Worksheet.ProtectionMode 属性来确定工作表是否受保护(而不是尝试 try..catch),并尝试 Unprotect("") 尝试使用空白密码取消保护工作表。

【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2011-01-18
    • 1970-01-01
    • 2012-05-21
    • 2011-04-15
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多