8
votes

I am using Apache POI to generate Exccel Templete which my clients could download, add values and upload back.

I would like to set the cell values non editable so that the template headers could not be edited.

I tried this code but it does not work,

    cell.getCellStyle().setLocked(true)

I also read that locking the excel sheet and then allowing the columns to setlocked(false) would work but I am not sure how many columns will be filled by client, so I want is all other columns t be edited except the one which I filled dynamically with Apache POI.

I hope my query is clear to understand.

2

2 Answers

3
votes

Try the following code, it may solve your problem:

HSSFWorkbook workbook = new XSSFWorkbook(); 

// Cell styles. Note the setLocked(true) method call. 
HSSFCellStyle lockedNumericStyle = workbook.createCellStyle(); 
lockedNumericStyle.setAlignment(XSSFCellStyle.ALIGN_RIGHT); 
lockedNumericStyle.setLocked(true); 

HSSFSheet sheet = workbook.createSheet("Protection Test"); 
HSSFRow row = sheet.createRow(0); 
HSSFCell cell = row.createCell(0); 
cell.setCellValue(100); 
cell.setCellStyle(lockedNumericStyle); 

// This line should cause all locked cells to be protected, 
// the user should not be able to change the cells 
// contents. 
sheet.protectSheet("password"); 

The password makes it possible to remove the protection from the sheet and makes it possible then for the locked cells to be modified. 
0
votes

I don't recall how well this works -- for example, I think that the client can unprotect the sheet using the menu -- but you do need to protect the sheet via something like Sheet.protectSheet("") (no password, but nevertheless a protected sheet.)