I have a problem during the generation of an excel file with protection using Apache POI 3.17. I have to unlock some cell after protecting the file, but when I download the file, the entire sheet is protected including the unlocked cells. Following is the code used:
String startFilePath = storageService.getPathName()+ File.separator + storageService.getNameStoreFile();
try ( FileInputStream inputStream = new FileInputStream(new File(startFilePath));
Workbook workbook = startFilePath.endsWith("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream) ){
Sheet sheet = workbook.getSheetAt(0);
sheet.protectSheet("password");
CellStyle cs = workbook.createCellStyle();
cs.setLocked(false);
Row row = sheet.getRow(0);
if(row == null){
row = sheet.createRow(0);
}
Cell cell = row.getCell(0);
if(cell == null){
cell = row.createCell(0);
}
setValue(cell, "A value");
cell.setCellStyle(cs);
}
String tmpNewFileNamePath = storageService.getPathName() + File.separator + "_TMP_" + storageService.getNameStoreFile();
File targetFilePath = new File(tmpNewFileNamePath);
//save workbook
FileOutputStream fileOut = new FileOutputStream(targetFilePath);
workbook.write(fileOut);
fileOut.close();
//remove startFile
FileUtils.forceDelete(new File(startFilePath));
//rename endFile to startFile
FileUtils.moveFile(targetFilePath, new File(startFilePath));