【发布时间】: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