Unable to set the password protection on aspose.cells WorkSheet

I am creating workbook using aspose.cells and trying to set the password protection on certain worksheets, but somehow it is not getting set.

Below is my code:

 Workbook _workBook = new Workbook(memoryStream);
 Worksheet worksheet = _workBook.Worksheets["Test"];
 
 worksheet.Protect(ProtectionType.All, "Test123", null);

Any suggestions, what’s missing here?

@sachingangarde,

Thanks for your query.

See the documents with example code in the section on how to protect worksheets in the workbook for your complete reference:

In case, you still find any issue, kindly do provide your sample code (runnable) with template file, we will check it soon.

Thanks for your response. I followed same documentation, but somehow it is not setting the password protection. Code throws no error.

I will post the code soon.

Here is the code :

 byte[] fileContent = null;
        using (FileStream fs = File.OpenRead(@"C:\test\test3.xlsx"))
        { 
            fileContent = new byte[fs.Length];
            fs.Read(fileContent, 0, Convert.ToInt32(fs.Length));
            fs.Close(); 
        }
 ms = new MemoryStream();
 ms.WritefileContent 0, fileContent .Length);
 ms.Position = 0;

Workbook  _workBook = new Workbook(memoryStream);
/*
created sheets in between
*/

Worksheet worksheet = _workBook.Worksheets[sheetName];
 
worksheet.Protect(ProtectionType.All, password, null);

  _workBook.CalculateFormula();
  _workBook.Save(_filePath);

@sachingangarde,

Thank you for the sample code. I have tried it and found it working fine using the latest version Aspose.Cells for .NET 19.7.3. I opened the output workbook containing protected worksheet in Excel and checked the worksheet protection. Its behaviour was as expected and Excel displayed the message (image attached) while editing it. You may please give it a try and share the feedback.

Workbook _workBook = new Workbook(path + "Book1.xlsx");
_workBook.Worksheets.Add("NewSheet");
Worksheet worksheet = _workBook.Worksheets["NewSheet"];
worksheet.Protect(Aspose.Cells.ProtectionType.All, "Test123", null);
_workBook.Save(path + "output.xlsx");

Book1.zip (6.1 KB)
output.zip (7.0 KB)
SheetProtection.PNG (25.5 KB)

You may download the latest version here:
Aspose.Cells19.7.3 For .Net2_AuthenticodeSigned.Zip (4.9 MB)
Aspose.Cells19.7.3 For .Net4.0.Zip (4.9 MB)