Search code examples
officewriter

Is cell locking is possible in excel using officewriter?


I need to lock a particular cell value in an Excel file using OfficeWriter. Is this possible? If so, what API calls do I need to use?


Solution

  • Locking a cell with OfficeWriter is the same as it is in Excel: all cells have a 'locked' property as part of their style. The locked property is set to true by default, but does not take affect until the worksheet is protected.

    ExcelApplication xla = new ExcelApplication();
    Workbook wb = xla.Create(ExcelApplication.FileFormat.Xlsx);
    Worksheet ws = wb.Worksheets[0];
    
    //Protecting the sheet will lock any cells 
    //that have the locked property set to true
    ws.Protect("MyPassword");
    

    To leave certain cells unlocked, create a style where the locked property is set to false. Then apply the style to the cells you wish to leave unlocked.

    ExcelApplication xla = new ExcelApplication();
    Workbook wb = xla.Create(ExcelApplication.FileFormat.Xlsx);
    Worksheet ws = wb.Worksheets[0];
    
    //Create the 'unlocked' style
    Style unlockedStyle = wb.CreateStyle();
    unlockedStyle.CellLocked = false;
    
    //Apply to any cells you wish to leave unlocked
    //when the worksheet is protected
    ws.Cells["A1"].Style = unlockedStyle;
    ws.Cells["B1"].Style = unlockedStyle;
    
    
    //Protecting the sheet will lock any cells 
    //that have the locked property set to true
    ws.Protect("MyPassword");
    

    We have some additional related information on protecting worksheets in our documentation: http://wiki.softartisans.com/display/EW8/Protecting+Your+Worksheet

    Note, I work for SoftArtisans, makers of OfficeWriter.