Document Solutions for Excel, Java Edition | Document Solutions
Features / Worksheet / Range Operations / Protect Cell Range
In This Topic
    Protect Cell Range
    In This Topic

    DsExcel allows you to protect cells in a worksheet by locking the cells or hiding the formulas in the cells with setLocked and setFormulaHidden methods of IRange and IStyle interfaces.

    Interface Method Description
    IRange setLocked Locks specific cell range of a worksheet.
    setFormulaHidden Hides formulas in a specific cell range of a worksheet.
    IStyle setLocked Locks all worksheet cells with style.
    setFormulaHidden Hides formulas in all worksheet cells with style.

    Note: By default, setLocked method is set to true, and setFormulaHidden method is set to false.

    Note: setLocked and setFormulaHidden methods will work when the worksheet is protected. For more information on protecting a worksheet, see Protect a Worksheet.

    Lock Cells

    Lock Specific Cell Range

    Refer to the following example code to lock a specific cell range of a worksheet when protected:

    Java
    Copy Code
    // Lock cell range C7:C11. 
    worksheet.getRange("C7:C11").setLocked(true);

    Lock Worksheet Cells with Style

    Refer to the following example code to lock worksheet cells with style when protected:

    Java
    Copy Code
    // Lock cells with custom style.
    IStyle style = workbook.getStyles().add("CustomStyle");
    style.setLocked(true);
    worksheet.getRange("B2:D18").setStyle(style);

    By default, all the cells in a worksheet have "Normal" style, and you can lock all the worksheet cells by setting setLocked method of the style of any cell. Refer to the following example code to lock all the worksheet cells:

    Java
    Copy Code
    // Lock all worksheet cells.
    worksheet.getRange("A1").getStyle().setLocked(true);

    Hide Formula in Cells

    Hide Formula in Specific Cell Range

    Refer to the following example code to hide formulas in a specific cell range of a worksheet when protected:

    Java
    Copy Code
    // Hide formula(s) in cell range C7:C19. 
    worksheet.getRange("C7:C19").setFormulaHidden(true);

    Hide Formula in Worksheet Cells with Style

    Refer to the following example code to hide formulas in all worksheet cells with a specific style when protected:

    Java
    Copy Code
    // Hide formula in cells with custom style.
    IStyle style = workbook.getStyles().add("CustomStyle");
    style.setFormulaHidden(true);
    worksheet.getRange("B2:D18").setStyle(style);

    By default, all the cells in a worksheet have "Normal" style, and you can hide formulas in all the worksheet cells by setting setFormulaHidden method of the style of any cell. Refer to the following example code to hide the formula in all the worksheet cells:

    Java
    Copy Code
    // Hide formula in all worksheet cells.
    worksheet.getRange("A1").getStyle().setFormulaHidden(true);