Generally speaking, people may protect one important document or file by giving a password for it, especially some important or secret files. For office workers, they often record important data in Excel. Therefore, they need to know clearly about how to protect Excel file.

There are several methods to protect Excel file. We can lock the whole worksheet to prevent others from opening or editing it. Also, we can just protect specified Excel rangeor cells.

Firstly, I want to talk something about using MS to protect Excel.

Method 1:

Select all cells or range which you want to lock, and then click Cells on Format menu. Select Protect tab. Check Lock checkbox.

Method 2:

Click Protect on Tool menu. Choose Protect Worksheet. Then type the password twice. Click OK.

Method 3:

Click Protect on Tool menu. Then choose Allow users to editing range. Click Create New on the pops-up window. Select range you want to lock. You can set several passwords for different ranges.

After learning how to protect Excel by using MS, I want to share another method through programming. Actually, programmers often need to use C# to protect Excel worksheet. But if they don’t install MS on computer, how can they do to complete the operation? Now, the method I will introduce is to solve this problem.

Note: A component, Spire.XLS is needed to be installed before using the following code:

Private Sub btnRun_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRun.Click

{    

      workbook As Workbook = New Workbook()

      //Initailize worksheet

      workbook.CreateEmptySheets(1)

      sheet As Worksheet = workbook.Worksheets(0)

      //Protect workshet

      sheet.Protect(Me.textBox1.Text)

      //Protect cells

      sheet.Range("A1").Text = "Locked"

      sheet.Range("B1").Text = "Unlocked"

      sheet.Range("A1").Style.Locked = True

      sheet.Range("B1").Style.Locked = False

      //Protect workbook

      workbook.Protect(Me.textBox1.Text)

      workbook.SaveToFile("Sample.xls")

      ExcelDocViewer(workbook.FileName)

}

Private Sub ExcelDocViewer(ByVal fileName As String)

{

       try

       {

             System.Diagnostics.Process.Start(fileName)

       }

       Catch{}

}