Apache POI - How to protect sheet with options?

前端 未结 2 1911
情深已故
情深已故 2020-12-05 06:00

I\'m using the Apache POI to generate an Excel File (2007). What I want is to protect the sheet, but with some options enabled. By options I mean the check box list when you

相关标签:
2条回答
  • 2020-12-05 06:15

    In Apache POI 3.9 you can use XSSF Sheet protection by enabling lock functions. even you can leave behind few excel objects unlocked as in case below I left out excel object (i.e text box) unlocked and rest are locked.

     private static void lockAll(Sheet s, XSSFWorkbook workbookx){
        String password= "abcd";
        byte[] pwdBytes = null;
        try {
            pwdBytes  = Hex.decodeHex(password.toCharArray());
        } catch (DecoderException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        XSSFSheet sheet = ((XSSFSheet)s);
        removePivot(s,workbookx);
        sheet.lockDeleteColumns();
        sheet.lockDeleteRows();
        sheet.lockFormatCells();
        sheet.lockFormatColumns();
        sheet.lockFormatRows();
        sheet.lockInsertColumns();
        sheet.lockInsertRows();
        sheet.getCTWorksheet().getSheetProtection().setPassword(pwdBytes);
        for(byte pwdChar :pwdBytes){
            System.out.println(">>> Sheet protected with '" + pwdChar + "'");
        }
        sheet.enableLocking();
    
        workbookx.lockStructure();
    
    }
    
    0 讨论(0)
  • 2020-12-05 06:39

    You might encounter that you can't select which features, it's either all or nothing. This is currently a known bug in Apache Poi. Source: https://issues.apache.org/bugzilla/show_bug.cgi?id=51483

    You can fix this by using the following workaround:

      xssfSheet.enableLocking();
      CTSheetProtection sheetProtection = xssfSheet.getCTWorksheet().getSheetProtection();
      sheetProtection.setSelectLockedCells(true); 
      sheetProtection.setSelectUnlockedCells(false); 
      sheetProtection.setFormatCells(true); 
      sheetProtection.setFormatColumns(true); 
      sheetProtection.setFormatRows(true); 
      sheetProtection.setInsertColumns(true); 
      sheetProtection.setInsertRows(true); 
      sheetProtection.setInsertHyperlinks(true); 
      sheetProtection.setDeleteColumns(true); 
      sheetProtection.setDeleteRows(true); 
      sheetProtection.setSort(false); 
      sheetProtection.setAutoFilter(false); 
      sheetProtection.setPivotTables(true); 
      sheetProtection.setObjects(true); 
      sheetProtection.setScenarios(true);
    
    0 讨论(0)
提交回复
热议问题