简体   繁体   中英

Apache POI - Excel Write - Lock Single Cell

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.

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. 

我不记得这样做的效果如何-例如,我认为客户端可以使用菜单取消保护工作表-但您确实需要通过Sheet.protectSheet("")类的Sheet.protectSheet("")保护工作表(无需输入密码,但仍然是受保护的表。)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM