DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironsoftware.com

Protect Excel Files

When you share an Excel file with other users, you may want to protect a worksheet to help prevent it from being changed.

IronXL allows you to both Protect and Unprotect any Excel WorkSheet with a single line of C# code.

C#:

using IronXL;

WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet worksheet = workbook.DefaultWorkSheet;

//This is how we can protect the worksheet setting the password to it
//Users will then need to know this password to edit the worksheet in Excel.
worksheet.ProtectSheet("password");
workbook.Save();

//This is how to unprotect the worksheet and remove any password locks 
//It works even if you do not know the password!
worksheet.UnprotectSheet();
workbook.Save();
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronXL

Private workbook As WorkBook = WorkBook.Load("test.xlsx")
Private worksheet As WorkSheet = workbook.DefaultWorkSheet

'This is how we can protect the worksheet setting the password to it
'Users will then need to know this password to edit the worksheet in Excel.
worksheet.ProtectSheet("password")
workbook.Save()

'This is how to unprotect the worksheet and remove any password locks 
'It works even if you do not know the password!
worksheet.UnprotectSheet()
workbook.Save()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)