Created
February 25, 2021 12:27
-
-
Save zhongxiao37/845493109b120bdc1f6ba7153a36f380 to your computer and use it in GitHub Desktop.
Encrypt the XLSX file with password by using POI
This file contains hidden or 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
```groovy | |
// http://poi.apache.org/encryption.html | |
import org.apache.poi.poifs.filesystem.POIFSFileSystem | |
import org.apache.poi.poifs.crypt.EncryptionInfo | |
import org.apache.poi.poifs.crypt.Encryptor | |
import org.apache.poi.poifs.crypt.EncryptionMode | |
import org.apache.poi.openxml4j.opc.OPCPackage | |
import org.apache.poi.openxml4j.opc.PackageAccess | |
import org.apache.poi.xssf.streaming.SXSSFWorkbook | |
void encryptExcel(String filePath) { | |
POIFSFileSystem fs = new POIFSFileSystem() | |
Encryptor enc = new EncryptionInfo(EncryptionMode.agile).getEncryptor() | |
enc.confirmPassword("12345678") | |
OPCPackage opc = null | |
OutputStream os | |
try { | |
opc = OPCPackage.open(filePath, PackageAccess.READ_WRITE) | |
os = enc.getDataStream(fs) | |
opc.save(os) | |
} | |
finally { | |
if (opc != null){ | |
opc.close() | |
} | |
if (os != null){ | |
os.close() | |
} | |
} | |
deleteFileIfExists(new File(filePath).toPath()) | |
FileOutputStream fos = null | |
try { | |
fos = new FileOutputStream(new File(filePath)) | |
fs.writeFilesystem(fos) | |
} | |
finally { | |
if (fos != null){ | |
fos.close() | |
} | |
} | |
fs.close() | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
try (POIFSFileSystem fs = new POIFSFileSystem()) {
EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
// EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha384, -1, -1, null);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");
// Read in an existing OOXML file and write to encrypted output stream
// don't forget to close the output stream otherwise the padding bytes aren't added
try (OPCPackage opc = OPCPackage.open(new File(""), PackageAccess.READ_WRITE);
OutputStream os = enc.getDataStream(fs)) {
opc.save(os);
}
// Write out the encrypted version
try (FileOutputStream fos = new FileOutputStream("C:\.xlsx")) {
fs.writeFilesystem(fos);
}
}