-1

I have created the excel file but i want protect my excel file and set the password. Please anyone help me how to set the password for my excel(.xls) file

Sample code:

FileOutputStream fileOut = null;
try {
    // Create a new workbook
    HSSFWorkbook workbook = new HSSFWorkbook();

    // create styles to use in work book
    Map<String, HSSFCellStyle> styles = createStyles(workbook);

    HSSFSheet worksheet = null;

    if (individualVOList != null && !individualVOList.isEmpty()) {
        worksheet = workbook.createSheet(DBElement.INDIVIDUALS.getName());

        // Construct the header for the report
        constructPageHeader(worksheet, styles.get("pageTitle"), DBElement.INDIVIDUALS.getName());

        constructTableContent(worksheet, styles, individualVOList);
    }

    fileOut = new FileOutputStream(excelFile);
    workbook.write(fileOut);
    fileOut.close();

    status = true;
} catch (FileNotFoundException ex) {
    System.out.println("[PL] - FileNotFoundException " + ex);
} catch (IOException ex) {
    System.out.println("[PL] - IOException " + ex);
}
Kaan
  • 5,434
  • 3
  • 19
  • 41
Thadeuse
  • 1,713
  • 2
  • 12
  • 19
  • 1
    I don't see any code that tries to set a password in what you posted. Why do you expect a password to be set in the above code? Am I missing something? – Robert Sep 27 '19 at 02:13
  • https://stackoverflow.com/questions/41354454/i-want-to-create-a-password-protected-excel-file-using-apache-poi-and-then-give/41357914 – Mohamed Saligh Sep 27 '19 at 02:41

1 Answers1

2

From your code, you are using HSSFWorkbook, which has Javadoc here. In that Javadoc, there is a method called writeProtectWorkbook. It looks like this:

public void writeProtectWorkbook(java.lang.String password,
                                 java.lang.String username)

protect a workbook with a password (not encypted, just sets writeprotect flags and the password.

(looks like they're missing a right parentheses in their javadoc, minor typo)

So in your code, the Javadoc says you could do something like this to protect the document with username scooter, password s3cr3t:

HSSFWorkbook workbook = new HSSFWorkbook();
workbook.writeProtectWorkbook("s3cr3t", "scooter");
Kaan
  • 5,434
  • 3
  • 19
  • 41