工作表。无保护 – Office Interop – 2003年和2007年之间的差异

我有一个.NET的WinForms应用程序自动化Excel和检查工作表密码。 要求能够检测到1)保护被closures2)密码被移除(被保护,但没有密码)3)密码与来自数据库的正确密码匹配

为了满足第二个要求,程序调用带有空string的Worksheet.Unprotect命令,捕获错误。 如果出现错误,则进行第三次检查。 如果没有错误,那么取消保护工作没有密码==>密码被删除。

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

该应用程序可以做到这一点与Office 2003的罚款。我有我的开发机更新到Office 2007,它不再像以前那样工作。 当我打电话给Worksheet.Unprotect,Excel提示input密码!

我需要知道如何在新版本的Excel中完成这项工作,或者如果有办法引用旧的PIA。 无论如何设置Excel 11的引用,在GAC中将其replace为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 

使用Worksheet.ProtectionMode属性来确定工作表是否受到保护(而不是try..catch尝试),并尝试使用Unprotect(“”)尝试解除空白密码工作表的保护。