Protect Microsoft Excel Sheet in C#

 

In my previous article we discuss about how to add validations for Excel sheet. Today we discuss about how to protect Excel sheet. Sometimes we may have requirement to protect excel sheet from our users, that means providing excel sheet to users in read only format. To protect the excel sheet Microsoft Office.Interop.Excel library providing the Protect method for Worksheet. 

To protect the Excel sheet first we have to create Excel Sheet and then call Protect method for Excel sheet as shown below. 

using System; 

using System.Diagnostics; 

using System.Reflection; 

using System.Windows.Forms; 

using Excel = Microsoft.Office.Interop.Excel;

 

namespace CSharpProtectExcel 

{ 

    public partial class Form1 : Form 

    {

        public Form1() 

        { 

            InitializeComponent(); 

        }

 

        private void button1_Click(object sender, EventArgs e) 

        { 

            Excel.Application oXL = new Excel.Application(); 

            Excel.Workbook oWB = oXL.Workbooks.Add(Missing.Value); 

            Excel.Worksheet oWS = oWB.Worksheets[1] as Excel.Worksheet; 

            string sPwd = "abc@123"; 

 

             //rename the Sheet 

            oWS.Name = "Excel Sheet"; 

            oWS.Cells[1, 1] = "Ths is Protected Sheet, try to edit the content";

 

            oWS.Protect(sPwd, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing, 

                Type.Missing 

                );

 

            oWB.SaveAs(Application.StartupPath + "\\ProtectedExcel.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

 

            oWB.Close(true, Missing.Value, Missing.Value); 

            Process.Start(Application.StartupPath + "\\ProtectedExcel.xlsx"); 

        } 

    } 

}

 

As shown above we are creating the Excel Worksheet, rename it to "Excel Sheet" and calling the Protect method, passing the password as "abc@123". Then click on "Protect Excel Sheet" button and try to edit the Excel sheet, you will get below error. 

                                                                                                                   CSharpProtectExcel.zip (1.05 mb)