The simplest and most efficient way to keep your Excel file confidential is to encrypt the whole workbook or the specified worksheet with password. Apart from setting a password for your document, you could also choose whether to protect workbook structure or protect worksheet with a certain protection type.
In this article, I am going to introduce how to password protect a workbook or a worksheet as well as set specified permissions to control what types of changes people can make to this workbook using Spire.XLS for WPF.
Code Snippets:
Step 1: Initialize a new instance of workbook class and load an existing Excel file.
Workbook wb = new Workbook(); wb.LoadFromFile("sample.xlsx", ExcelVersion.Version2013);
Step 2: Call Workbook.Protect(string passwordToOpen, bool bIsProtectWindow, bool bIsProtectContent) to protect the workbook with password and also protect the workbook window and structure.
wb.Protect("password-1",true,true);
Step 3: Get the third worksheet from workbook, call protect method of XlsWorksheetBase class to encrypt the sheet with password and set the protection type as None which represents no changes are allowed in the protected sheet. Besides None, there are 17 others in SheetProtectionType enum that can help you to set different permissions to command what users can do to this worksheet.
Worksheet sheet = wb.Worksheets[2]; sheet.Protect("password-2", SheetProtectionType.None);
Step 4: Save and launch the file.
wb.SaveToFile("ProtectedExcel.xlsx"); System.Diagnostics.Process.Start("ProtectedExcel.xlsx");
Output:
Protect Workbook
Protect Worksheet
Full Code:
using Spire.Xls; using System.Windows; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Workbook wb = new Workbook(); wb.LoadFromFile("sample.xlsx", ExcelVersion.Version2013); wb.Protect("password-1", true, true); Worksheet sheet = wb.Worksheets[2]; sheet.Protect("password-2", SheetProtectionType.None); wb.SaveToFile("ProtectedExcel.xlsx"); System.Diagnostics.Process.Start("ProtectedExcel.xlsx"); } } }
Imports Spire.Xls Imports System.Windows Namespace WpfApplication1 Public Partial Class MainWindow Inherits Window Public Sub New() InitializeComponent() End Sub Private Sub button1_Click(sender As Object, e As RoutedEventArgs) Dim wb As New Workbook() wb.LoadFromFile("sample.xlsx", ExcelVersion.Version2013) wb.Protect("password-1", True, True) Dim sheet As Worksheet = wb.Worksheets(2) sheet.Protect("password-2", SheetProtectionType.None) wb.SaveToFile("ProtectedExcel.xlsx") System.Diagnostics.Process.Start("ProtectedExcel.xlsx") End Sub End Class End Namespace