Locking cells in a JXL-generated Excel document
Is there a way to lock certain cells from being edited by the user? I have tried the following:
WritableCellFormat cf = new WritableCellFormat();
cf.setLocked(true);
sheet.addCell(new Number(col, row, value, cf));
However this doesn't seem开发者_Go百科 to have any effect on the resulting spreadsheet i.e. the cell contents can still be changed when the file is opened in Excel.
you have to "activate" protection for each sheet. I'm not shure how exactly this should be done. The method I found is
sheet.setProtected(true);
but obviously this method is no longer recommended. So You should probably try to find some newer one.
edit: sorry, my mistake. This lock every cell in the sheet.
edit 2: It works for me if you lock entiry sheet and then unlock editable cells.
sheet.getSettings().setProtected(true);
WritableCellFormat unlocked = new WritableCellFormat();
unlocked.setLocked(false);
Label l = new Label(0, 0, "", unlocked);
sheet.addCell(l);
Here are the general steps for protecting a cell without using the deprecated methods in the accepted answer
1. Create a WritableCellFormat object and set locked to false
2. When you add a cell that you want to be unlocked include the WritableCellFormat in the addCell(...) method call
3. Call getSettings on the sheet to get the SheetSettings object and call setProtected(true) to protect the sheet and by extension the protected cells which in excel by default is all the cells.
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setLocked(false)
WritableSheet sheet = Worksheet.createSheet();
//Create a cell that is protected and a cell that is not protected
sheet.addCell(new Label(col1, row, "My Locked Cell");
sheet.addCell(new Label(col2, row, "My Unlocked Cell", cellFormat);
//Protect the sheet so that locked cells are locked and unlocked cells are unlocked
sheet.getSettings().setProtected(true);
In newer versions you should do
sheet.protectSheet("password");
Noticed that template file should be protected as well in preferences. Otherwise protection didn't work properly for me in LibreOffice, sheet looks like "hanged", you can't even click on cell. Explicitly made protected solved problem, but you should toggle checkboxes for "use protected cells" or smth like that. P.S. I made protection with password, but it's not used in final file (password comes from code)
精彩评论