【问题标题】:Apache POI - How to protect sheet with options?Apache POI - 如何使用选项保护工作表?
【发布时间】:2013-01-20 00:19:10
【问题描述】:

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

【问题讨论】:

  • 我不认为超越sheet.getSettings() set() 方法,你可以做任何事情。
  • sheet.getSettings() 我认为来自 JExcel,而不是 Apache POI。

标签: java excel-2007 apache-poi


【解决方案1】:

您可能会遇到无法选择哪些功能,要么全有,要么全无。这是当前 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);

【讨论】:

  • 我正在使用 XSSFSheet 对象。有没有办法在我的工作表受到保护的情况下启用 Excel 中的清除所有过滤器选项。?有什么建议吗?
【解决方案2】:

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

}

【讨论】:

  • 您能解释一下removePivot(s,workbookx); 的来源吗?另外,这个答案在 poi-ooxml 3.17 上是否发生了变化?
  • 另外,在 v. 3.17 上使用此代码,减去removePivot(s,workbookx);,我能够打开保存的 XLSX,但随后在不输入密码的情况下取消单击“保护表”。然后,我可以随心所欲地修改工作表。
  • @KevinMeredith:要完成这项工作,您必须使用密码调用 WorkSheet 对象的protectSheet 方法。有了这个,保护就不能再被删除了。
猜你喜欢
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 2014-07-02
  • 2017-12-21
  • 1970-01-01
相关资源
最近更新 更多