Created
August 11, 2023 00:51
-
-
Save levancho/73a3d2dba9f248ade097ad007c0e9c7d to your computer and use it in GitHub Desktop.
password protect excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] passwordProtectExcel(byte[] inputExcel) throws IOException, GeneralSecurityException { | |
// Convert the input byte array to a Workbook | |
XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(inputExcel)); | |
// Prepare to encrypt the workbook | |
POIFSFileSystem fs = new POIFSFileSystem(); | |
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); | |
Encryptor enc = info.getEncryptor(); | |
enc.confirmPassword("password"); // Set the password here | |
// Write the Workbook to an encrypted OutputStream | |
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { | |
workbook.write(os); | |
os.close(); | |
try (ByteArrayOutputStream encOs = new ByteArrayOutputStream()) { | |
enc.encryptDocument(os, encOs); | |
encOs.close(); | |
fs.writeFilesystem(encOs); | |
return encOs.toByteArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment