Skip to content

Instantly share code, notes, and snippets.

@zhongxiao37
Created February 25, 2021 12:27
Show Gist options
  • Save zhongxiao37/845493109b120bdc1f6ba7153a36f380 to your computer and use it in GitHub Desktop.
Save zhongxiao37/845493109b120bdc1f6ba7153a36f380 to your computer and use it in GitHub Desktop.
Encrypt the XLSX file with password by using POI
```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()
}
```
@nosiyBUGS
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment