Locking cells

Hello,

I believe this must be possible by the way it looks so far, but can you lock certain cells from being accessed while allowing others to be edited? I see the example in the demo's for locking the worksheet but we have a requirement to lock only certain fields.

Hi,

Thanks for considering Aspose.

Well Yes, you can lock a cell, a complete row or a complete column in the worksheet easily. Please utilize the following code snippets

1. Lock a cell (A1) in the worksheet:

Workbook wb = new Workbook();

Worksheet sheet = wb.Worksheets[0];

Style style;

for(int i = 0; i <= 255; i ++)

{

style = sheet.Cells.Columns[(byte)i].Style;

style.IsLocked = false;

}

style = sheet.Cells["A1"].Style;

style.IsLocked = true;

Aspose.Cells.Protection protection = sheet.Protection;

wb.Save("d:\\lockedcell.xls", FileFormatType.ExcelXP);

2. Lock a complete row (First Row) in the worksheet:

Workbook wb = new Workbook();

Worksheet sheet = wb.Worksheets[0];

Style style;

StyleFlag flag;

for(int i = 0; i <= 255; i ++)

{

style = sheet.Cells.Columns[(byte)i].Style;

style.IsLocked = false;

flag = new StyleFlag();

flag.Locked = true;

sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag);

}

style = sheet.Cells.Rows[0].Style;

style.IsLocked = true;

flag = new StyleFlag();

flag.Locked = true;

sheet.Cells.Rows[0].ApplyStyle(style, flag);

Aspose.Cells.Protection protection = sheet.Protection;

wb.Save("d:\\lockedcells.xls", FileFormatType.ExcelXP);

Regards

Amjad Sahi

Aspose Nanjing Team

Hello,

Thanks for the info on Locking cells, but I'm having a problem with this. I use the Style objects setCellLocked(true) method to set the cells to locked that apply that style. When I run this all of the cells are unlocked, I then tried password protecting the worksheet which just locked all of the cells and I couldn't change any of them. Is there something I need to do after locking the cells?

Workbook wb = new Workbook();

Worksheets wss = wb.getWorksheets();

Worksheet testSheet= wss.getSheet(0);

Cells cells = testSheet.getCells();

Style headerRowStyle = wb.createStyle();

headerRowStyle.setName("headerRowStyle");

headerRowStyle.setCellLocked(true);

Style labelRowStyle = wb.createStyle();

labelRowStyle.setName("labelRowStyle");

labelRowStyle.setCellLocked(false);

Row headerRow = cells.getRow(0);

Cell headerCell = headerRow.getCell(0);

headerCell.setValue("Test Locked");

headerCell.setStyle(wb.getNamedStyle("headerRowStyle"));

Row labelRow = cells.getRow(1);

Cell labelCell = labelRow.getCell(0);

labelCell.setValue("Test Unlocked");

labelCell.setStyle(wb.getNamedStyle("labelRowStyle"));

wb.save(out);

This wouldn't lock the cells, and when I added Protection to the worksheet, it just locks all the cells.

Hi,

You must add Protection to the worksheet to make IsCellLocked effected.If the cell is locked ,you could not modify the content of the cell .If the cell is not locked, you still can modify the content of the cell.