0

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));
chrisblo
  • 768
  • 1
  • 13
  • 30
  • 1
    [Works for me in XSSFWorkbook created from scratch](https://stackoverflow.com/questions/48787000/apache-poi-lock-the-cell-but-allow-column-resize/48792180#48792180). Maybe you needs setting [XSSFSheet.lockSelectUnlockedCells(false)](https://poi.apache.org/apidocs/dev/org/apache/poi/xssf/usermodel/XSSFSheet.html#lockSelectUnlockedCells-boolean-). – Axel Richter Nov 09 '18 at 14:30
  • Thanks, now it works! – chrisblo Nov 09 '18 at 17:35

0 Answers0