Protect and Unprotect Worksheet with C++

Protect and Unprotect Worksheet in MS Excel

protect and unprotect Worksheet

  1. Click Review > Protect Worksheet.
  2. Enter a password in the Password box.
  3. Select allow options.
  4. Select OK, re-enter the password to confirm it, and then select OK again.

Protect Worksheet Using Aspose.Cells for C++

Only need the following simple lines of code to implement protecting workbook structure of Excel files.

#include <iostream>
#include "Aspose.Cells.h"
using namespace Aspose::Cells;

int main()
{
    Aspose::Cells::Startup();

    // Create a new workbook
    Workbook workbook;

    // Get the first worksheet
    Worksheet sheet = workbook.GetWorksheets().Get(0);

    // Protect contents of the worksheet
    sheet.Protect(ProtectionType::Contents);

    // Protect worksheet with password
    sheet.GetProtection().SetPassword(u"test");

    // Save as Excel file
    workbook.Save(u"Book1.xlsx");

    std::cout << "Workbook created and protected successfully!" << std::endl;

    Aspose::Cells::Cleanup();
}

Unprotect Worksheet Using Aspose.Cells for C++

Unprotecting worksheet is easy with Aspose.Cells API. If worksheet is password-protected, a correct password is required.

#include <iostream>
#include "Aspose.Cells.h"

using namespace Aspose::Cells;

int main()
{
    Aspose::Cells::Startup();

    // Create a new workbook
    Workbook workbook(u"Book1.xlsx");

    // Get the first worksheet
    Worksheet sheet = workbook.GetWorksheets().Get(0);

    // Unprotect the worksheet with password
    sheet.Unprotect(u"password");

    // Save the workbook
    workbook.Save(u"Book1.xlsx");

    std::cout << "Worksheet unprotected successfully!" << std::endl;

    Aspose::Cells::Cleanup();
}

Advance topics