javascripttypescriptnpmexceljs

I have an issue with excel js property - protection{locked:true}


I am creating and downloading an excel sheet using excel.js. I have a task like making certain columns and rows uneditable. I searched for it, I got a way like giving protected{locked: true} should protect the cells and should be uneditable, but when i download the excel, iam still able to edit the cells.

mergedWorkbook.eachSheet((worksheet) => {
    const lastColumnIndex = worksheet.columns.length;

    const protectedColumns = [0, 1, 2, lastColumnIndex];

    // Protect specified columns
    worksheet.columns.forEach((column, columnIndex) => {
      if (protectedColumns.includes(columnIndex)) {
        column.eachCell((cell) => {
          cell.protection = {
            locked: true,
          };
        });
      }
    });

    // Protect header row
    worksheet.getRow(1).eachCell((cell) => {
      cell.protection = {
        locked: true,
      };
    });
  });

Solution

  • In excel.js, just setting the cell protection to locked will not make the cell uneditable. You also need to set the worksheet protection. Note that the default value for all cells' lock is true.

    So you need to:

    Example:

    mergedWorkbook.eachSheet((worksheet) => {
          const lastColumnIndex = worksheet.columns.length;
          const protectedColumns = [0, 1, 2, lastColumnIndex];
        
          // Unprotect all cells in the worksheet
          worksheet.eachRow((row) => {
            row.eachCell((cell) => {
              cell.protection = {
                locked: false
              };
            });
          });
        
          // Protect specified columns
          worksheet.columns.forEach((column, columnIndex) => {
            if (protectedColumns.includes(columnIndex)) {
              column.eachCell((cell) => {
                cell.protection = {
                  locked: true,
                };
              });
            }
          });
        
          // Protect header row
          worksheet.getRow(1).eachCell((cell) => {
            cell.protection = {
              locked: true,
            };
          });
        
          // Set the sheet protection property
          worksheet.protect({}, { selectLockedCells: true });
        
        });