Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 395
Dipendra Pokharel Avatar asked Sep 13 '13 02:09

Dipendra Pokharel


People also ask

How do I make an Excel column read only in Java?

The entire code is: Map<String, XSSFCellStyle> styles = new HashMap<String, XSSFCellStyle>(); XSSFCellStyle style5 = wb. createCellStyle(); XSSFFont headerFont = wb. createFont(); headerFont. setBold(true); style5.


1 Answers

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. 
like image 167
John specter Avatar answered Oct 28 '22 23:10

John specter