Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using OWC 11.0 in ASP.NET and C# to create excel file.
I need to protect/unprotect the sheet by a password. I tried to protect the sheet by following code.


string Password = "Password123";
object getPasswordFromUser =(object)Password;
xl.ActiveSheet.Protect(ref getPasswordFromUser, ref obj,
ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj, ref obj,
ref obj, ref obj, ref obj, ref obj, ref objTrue, ref obj);But it throws an exception "Exception from HRESULT: 0xE0040059"



Kindly help me to resolve this issue. Code works well if I miss the password.
Posted

1 solution

I have been searching for an answer to the same problem. I have found (by experimentation) that if you use something like this:

using OWC = Microsoft.Office.Interop.Owc11;


Then the following:

OWC.Worksheet owcWorkSheet = (OWC.Worksheet)xl.Worksheets[1];
            
            owcWorkSheet.Protection.Enabled = true;
            owcWorkSheet.Protection.AllowDeletingColumns = false;
            owcWorkSheet.Protection.AllowDeletingRows = false;
            owcWorkSheet.Protection.AllowFiltering = false;
            owcWorkSheet.Protection.AllowFormattingColumns = false;
            owcWorkSheet.Protection.AllowFormattingRows = false;
            owcWorkSheet.Protection.AllowHeadingRename = false;
            owcWorkSheet.Protection.AllowInsertingColumns = false;


This will lock the worksheet. I still have not found a way to get the password in there. Possibly it is set in a different way than you are using. Make sure that you unlock / lock all cells using the hidden method:

owcWorkSheet.Cells.set_Locked(false);
owcWorkSheet.Cells.get_Item(1, 3).set_Locked(true);



Or switch it around if you want the reverse (i.e. want all cells locked except for one of them.).

It seems that the owcWorkSheet.Protection.Enabled = true; is what locks the worksheet.

If I find out how to assign a password to OWC11, I will mention that here. Hope this helps a bit.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900