15

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

4

2 回答 2

14

在 Apache POI 3.9 中,您可以通过启用锁定功能来使用 XSSF 表保护。即使您可以留下一些未锁定的 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();

}
于 2013-04-02T08:20:03.147 回答
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);
于 2013-10-01T11:13:17.613 回答