Other API Samples C# logo

Password-Protected Files SpreadsheetGear API Sample

Description

SpreadsheetGear supports reading and writing password-protected and encrypted workbooks with Agile Encryption used by Excel 2013 and later, including default SHA-512 encryption for workbooks.

For non-encrypted / non-password protected workbooks you would typically open these using the SpreadsheetGear.Factory.GetWorkbook(...) method, but GetWorkbook(...) does not have an overload to accept a password. For password-protected workbooks you must first create an IWorkbookSet object and then call IWorkbookSet.Workbooks.Open(string pathToFile, string password).

This sample demonstrates opening a password-protected workbook (protected with the password "MyPassword123"). It then sets a cell value with the current date and time to prove that the file was opened and modified, then saves the file again. Once you download the resultant file you can open it in Excel, which will prompt you to enter the password, where you should see the date/time that we added to the file.

Sample Source Code

// First we need to create a workbook set.  This is needed so that we can access the 
// IWorkbookSet.Workbooks.Open(...) method that has an overload to accept a password.
SpreadsheetGear.IWorkbookSet workbookSet = SpreadsheetGear.Factory.GetWorkbookSet();

// Open the password-protected workbook in this workbook set, specifying the password 
// as the second argument.
SpreadsheetGear.IWorkbook workbook = workbookSet.Workbooks.Open(@"PasswordProtected.xlsx",
    "MyPassword123");

// Add a value to cell A2 to show that we successfully opened this file and modified it.
workbook.ActiveWorksheet.Cells["A2"].Value = "Modified at " + 
    DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ssK");

// Save the workbook.  This persists the same password to the file.
workbook.Save();

// Download a copy of the workbook and attempt to open it in Excel, which should prompt
// you to enter a password.  Enter "MyPassword123" and the file should open and show the
// value we specified above for cell A2.