How to check if xlsx file is password protected or not. we can check for xls file as follows
FileInputStream fin = new FileInputStream(new File(\"C:/Book1.xl
If you don't know what you have, but you know the password, then you should use WorkbookFactory.create and pass the password to it, eg
Workbook wb = WorkbookFactory.create(new File("protected.xls"),
"NiceSecurePassword");
WorkbookFactory
will identify the type, then call the appropriate decryption and workbook loading for you. If the file isn't protected, the password will be ignored
.
If you know for sure that the file is .xlsx
based, but aren't sure if it is protected or not, then you can do something like:
Workbook wb = null;
try {
wb = new XSSFWorkbook(new File("test.xlsx"));
} catch (EncryptedDocumentException e) {
// Password protected, try to decrypt and load
}
If you give the XSSFWorkbook a password protected .xlsx
file, it'll throw a EncryptedDocumentException which you can catch and then try decrypting, based on the code you've already got
First,
public boolean isEncrypted(String path) {
try {
try {
new POIFSFileSystem(new FileInputStream(path));
} catch (IOException ex) {
}
System.out.println("protected");
return true;
} catch (OfficeXmlFileException e) {
System.out.println("not protected");
return false;
}
}
then,
if (isEncrypted(sourcepath)) {
org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword("1234");
POIFSFileSystem filesystem = new POIFSFileSystem(new FileInputStream(inpFn));
EncryptionInfo info = new EncryptionInfo(filesystem);
Decryptor d = Decryptor.getInstance(info);
if (!d.verifyPassword("1234")) {
System.out.println("Not good");
} else {
System.out.println("Good!");
}
in = d.getDataStream(filesystem);
} else {
in = new FileInputStream(inpFn);
}
try {
XSSFWorkbook wbIn = new XSSFWorkbook(in);
.
.
.
Try using
XSSFWorkbook wb = new XSSFWorkbook(dataStream);
From Apache POI: "HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format." http://poi.apache.org/spreadsheet/ You're using the HSSF (which will work for xls) on a XLSX file.