Previous topicNext topic
Help > 开发指南 > Excel > API > 示例 > 保护 >
如何:对工作簿进行写保护

使用 Workbook.DocumentSettings.WriteProtection 属性可返回文档的写保护选项。

将工作簿设置为只读

启用 WriteProtectionOptions.ReadOnlyRecommended 选项,使工作簿设置为只读。

Vb.Net
'创建一个Workbook工作簿对象.
Using workbook As New DevExpress.Spreadsheet.Workbook()
    Dim wpOptions As DevExpress.Spreadsheet.WriteProtectionOptions = workbook.DocumentSettings.WriteProtection
    '使工作簿设置为只读
    wpOptions.ReadOnlyRecommended = True
    workbook.SaveDocument("D:\WriteProtectedDocument.xlsx")
End Using

C#
// 创建一个Workbook工作簿对象.
using (DevExpress.Spreadsheet.Workbook workbook = new DevExpress.Spreadsheet.Workbook())
{
    DevExpress.Spreadsheet.WriteProtectionOptions wpOptions = workbook.DocumentSettings.WriteProtection;
    // 使工作簿设置为只读
    wpOptions.ReadOnlyRecommended = true;
    workbook.SaveDocument(@"D:\WriteProtectedDocument.xlsx");
}

当用户在 Microsoft® Excel® 中打开此工作簿时,它会提示他们以只读方式打开文档。

指定用于修改工作簿的密码

调用 WriteProtectionOptions.SetPassword 方法以指定密码,以防止未经授权的用户进行修改。

Vb.Net
'创建一个Workbook工作簿对象.
Using workbook As New DevExpress.Spreadsheet.Workbook()
    Dim wpOptions As DevExpress.Spreadsheet.WriteProtectionOptions = workbook.DocumentSettings.WriteProtection
    '设置密码
    wpOptions.SetPassword("Password")
    wpOptions.UserName = "John Smith"
    workbook.SaveDocument("D:\WriteProtectedDocument.xlsx")
End Using

C#
// 创建一个Workbook工作簿对象.
using (DevExpress.Spreadsheet.Workbook workbook = new DevExpress.Spreadsheet.Workbook())
{
    DevExpress.Spreadsheet.WriteProtectionOptions wpOptions = workbook.DocumentSettings.WriteProtection;
    //设置密码
    wpOptions.SetPassword("Password");
    wpOptions.UserName = "John Smith";
    workbook.SaveDocument(@"D:\WriteProtectedDocument.xlsx");
}

当用户在 Microsoft® Excel® 中打开此工作簿时,它会提示他们输入密码来修改文档。

清除用于修改工作簿的密码

以下代码片段使用 WriteProtectionOptions.CheckPassword 方法检查给定的密码。如果密码有效,则调用 WriteProtectionOptions.ClearPassword 以从工作簿中删除写保护。

Vb.Net
'创建一个Workbook工作簿对象.
Using workbook As New DevExpress.Spreadsheet.Workbook()
    Dim wpOptions As DevExpress.Spreadsheet.WriteProtectionOptions = workbook.DocumentSettings.WriteProtection
    If wpOptions.IsPasswordProtected AndAlso wpOptions.CheckPassword("password") Then
        wpOptions.ClearPassword()
    Else
        MessageBox.Show("The file is not write-protected or the specified password is invalid!")
    End If
    workbook.SaveDocument("D:\WriteProtectedDocument.xlsx")
End Using

C#
// 创建一个Workbook工作簿对象.
using (DevExpress.Spreadsheet.Workbook workbook = new DevExpress.Spreadsheet.Workbook())
{
    DevExpress.Spreadsheet.WriteProtectionOptions wpOptions = workbook.DocumentSettings.WriteProtection;
    if (wpOptions.IsPasswordProtected && wpOptions.CheckPassword("password"))
        wpOptions.ClearPassword();
    else
        MessageBox.Show("The file is not write-protected or the specified password is invalid!");
    workbook.SaveDocument(@"D:\WriteProtectedDocument.xlsx");
}