使用VSTO和C# fx 3.5,如何检查Excel工作簿或工作表是否已加密?
Excel.Workbook myWorkbook = ...;
if (!myWorkbook.HasPassword)
{
excelWorkbook.Application.DisplayAlerts = false;
excelWorkbook.SaveAs(
excelWorkbook.Name,
Type.Missing,
"My Password",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
}
一个工作表可以保护其单元格内容、图形对象和/或方案。这些可以通过Worksheet.ProtectContents、Worksheet.ProtectDrawingObjects和Worsksheet.ProtectScenarios属性进行检查。我不知道有什么方法可以测试工作表是否受密码保护,除非尝试调用Worksheet.Unprotect,将空字符串作为密码传递,并查看工作表是否成功取消保护:
bool wasPasswordProtected;
try
{
myWorksheet.Unprotect(string.Empty);
// Unprotect suceeded:
wasPasswordProtected = false;
}
catch
{
// Unprotect failed:
wasPasswordProtected = true;
}
您可以通过Worksheet.Protect方法设置工作表的保护设置。以下示例将在任何三个保护元素未设置的情况下保护工作表。它还设置了密码,并将“UserInterfaceOnly”参数传递为“true”,这意味着仅阻止用户编辑工作表,而VBA、VB.NET或C#等代码不会被防止操纵工作表。将“UserInterfaceOnly”设置为“false”将锁定所有更改,无论是由用户还是通过代码进行的。
if(!myWorksheet.ProtectContents ||
!myWorksheet.ProtectDrawinngObjects ||
!myWorsksheet.ProtectScenarios)
{
string myPassword = "...";
bool protectContents = true;
bool protectDrawingObjects = true;
bool protectScenarios = true;
bool userInterfaceOnly = true;
myWorksheet.Protect(
myPassword,
protectDrawingObjects,
protectContents,
protectScenarios,
userInterfaceOnly,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
请查看HasPassword属性。
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlsApp = new Excel.Application();
xlsApp.DisplayAlerts = false;
Excel.Workbooks wkbs = xlsApp.Workbooks;
Excel.Workbook wkb;
try
{
wkb = wkbs.Open(path, ReadOnly: true, Password: "");
//If you don't send a string for the password, it will popup a window
//asking for the password and halt your program. If the workbook has no
//password, it will open just fine.
}
catch (Exception ex)
{
//If the file is password protected or otherwise unreadable, it will throw an exception.
}
wkb.Close(false);
xlsApp.Quit();