保护Apache POI上的工作表并解锁单元格

时间:2018-11-09 10:45:47

标签: excel apache-poi

使用Apache POI 3.17生成具有保护功能的excel文件时遇到问题。保护文件后,我必须解锁一些单元格,但是下载文件时,整个工作表都受到保护,包括未锁定的单元格。以下是使用的代码:

    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));

0 个答案:

没有答案