首页 文章

Apache POI - 如何使用选项保护工作表?

提问于
浏览
11

我正在使用Apache POI生成Excel文件(2007) . 我想要的是保护工作表,但启用了一些选项 . 通过选项我的意思是当您尝试保护Excel应用程序中的工作表时(在“允许此工作表的所有用户为:”标签下)的复选框列表 . 具体来说,我想启用“选择锁定/未锁定的单元格”,“格式列”,“排序”和“允许自动过滤” . 非常感谢你! :d

2 回答

  • 12

    在Apache POI 3.9中,您可以通过启用锁定功能来使用XSSF Sheet保护 . 即使你可以留下几个excel对象解锁,如下面我遗漏excel对象(即文本框)解锁和休息被锁定 .

    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();
    
    }
    
  • 5

    您可能会遇到无论是全部还是全无 . 这是Apache Poi中的一个已知错误 . 资料来源:https://issues.apache.org/bugzilla/show_bug.cgi?id=51483

    您可以使用以下解决方法解决此问题:

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

相关问题