title: Protecting certain cells in Excel - C# Epplus
body: <p>I have a program exporting a spreadsheet, containing headers and some data. I need to protect the headers, but leave the data cells editable. </p>
  
  <p>The problem is, upon setting the worksheet as protected, all the cells become read-only. </p>
  
  <p>So, the approach I am using is to check each of the cells below the header to see if they are not empty, and unlock them if so.</p>
  
  <pre><code>public void formatSpreadsheet(OfficeOpenXml.ExcelWorksheet ws)
  {
      // autofit columns
      for (int i = 1; i &lt;= ws.Dimension.End.Column; i++)
      {
          ws.Column(i).AutoFit();
      }
  
      // protect headers/metadata
      ws.Protection.IsProtected = true;
      int row = HEADER_ROW_OFFSET;
      int col = 1;
  
  
      while (ws.Cells[row,col].Value != null)
      {
  
          while (ws.Cells[row,col].Value != null)
          {
              ws.Cells[row, col].Style.Locked = false;
              col++;
          }
          row++;
      }
  
  }
  </code></pre>
  
  <p>Testing for null values like so:</p>
  
  <pre><code>if (ws.Cells[row,col].Value != null)  ws.Cells[row,col].Style.Locked = false;
  </code></pre>
  
  <p>doesn't work.</p>
  
  <p>I have also tried ToString() on the cell values, and it doesn't help.</p>
  
  <p>Any ideas?</p>