Skip to content

Make excel columns non editable using c#

Sanu

Asked Aug 22, 2013, 8:47 AM EDT3 answers
Share
LinkedInX
I have an excel sheet.
Want to make first 3 columns editable and remaining all columns non editable and blank (without grid lines) using c#. Please help...

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Sunny  Sharma
    0
    Hi sanu,

    You need to Unlock the whole sheet or the part which you want the user be able to edit and Lock the cells of your purpose.
    Protect the sheet when you're done and that's all it takes.

    try this way:
    -----------------------------------------------------------

    Missing mv = Missing.Value;
    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook wkb = excelApp.Workbooks.Add(mv);
    Microsoft.Office.Interop.Excel.Worksheet wks =(Microsoft.Office.Interop.Excel.Worksheet) wkb.Sheets[1];

    wks.Columns.Locked = false;
    ((Microsoft.Office.Interop.Excel.Range)wks.get_Range((object)wks.Cells[1, 1],(object) wks.Cells[1, 3])).EntireColumn.Locked = true;           
    wks.EnableSelection = Microsoft.Office.Interop.Excel.XlEnableSelection.xlUnlockedCells;
    wks.Protect(mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv, mv);

    wks.SaveAs("D:\\filename.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, mv, mv, mv, mv, mv, mv, mv, mv);
    wks = null;
    wkb = null;
    excelApp.Quit();
    ----------------------------------------------------------

    Happy Coding :)
    Cheers!!
    0
  • 0
    Thank you Sunny, will try this..
    0
  • 0
    Hi, here is another solution that you can try:
    C#
    // Load excel file.
    var file = ExcelFile.Load("input.xlsx");
    var sheet = file.Worksheets.ActiveWorksheet;
     
    // Set worksheet without grid lines.
    sheet.ViewOptions.ShowGridLines = false;
     
    // Set worksheet with protection.
    sheet.Protected = true;
     
    // Itarate through the required cells, set their borders and unlock them. 
    var range = sheet.Cells.GetSubrange("A1", "C" + sheet.Rows.Count);
    foreach (var cell in range)
    {
        cell.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);
        cell.Style.Locked = false;
    }
     
    // Save excel file.
    file.Save("output.xlsx");
    Code uses this .NET Excel dll, I find it to be a good alternative to an Excel Interop.
    0