Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

java - Apache POI - How to protect sheet with options?

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 try to protect the sheet in the Excel application (under the label "Allow all users of this worksheet to:"). Specifically, I want to enable "Select locked/unlocked cells", "Format Column", "Sort", and "Allow Autofilter". Thank you very much! :D

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...