如何检测excel(xls和xlsx)文件是否受密码保护?有没有要检查的旗帜? 注意:有两种类型可以为excel(xls / xlsx)提供密码:
我的代码仅适用于加密密码的xls。
对于上述失败的情况而不是一般异常,我想改进此代码。
使用的罐子:
POI-3.5-FINAL-20090928.jar
POI-3.7-20101029.jar
poi-ooxml-3.7-20101029.jar
public static String excelFileScanner(InputStream excelFileToScan,
String uploadFileExt) throws IOException {
String returnStatus = null;
try {
Workbook wb = null;// WorkbookFactory.create(excelFileToScan);
if (uploadFileExt.equalsIgnoreCase("xlsx")) {
wb = new XSSFWorkbook(excelFileToScan);
} else {
// POIFSFileSystem fs = new POIFSFileSystem(excelFileToScan);
wb = new HSSFWorkbook(excelFileToScan);
}
int noOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < noOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return "malicious";
}
}
}
}
returnStatus = "valid";
} catch (POIXMLException ex1) {
// catch (InvalidFormatException ex1) {
returnStatus = ex1.getClass().getSimpleName();
if (ex1 != null && ex1.getCause() != null) {
System.out.println("reason: " + ex1.getCause().toString());
System.out.println("passwordprotected");
} else {
System.out.println("else block: " + ex1);
}
} catch (EncryptedDocumentException ex2) {
returnStatus = "passwordProtected";
} catch (Exception ex) {
returnStatus = ex.getMessage();
}
return returnStatus;
}
public static void main(String[] args) throws IOException {
try {
File folder = new File("/Desktop/Excel/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
String uploadFileExt = null;
String filename = file.getName();
int extnSeparatorIndex = filename.lastIndexOf(".");
if (extnSeparatorIndex != -1) {
if (extnSeparatorIndex != file.length() - 1) {
uploadFileExt = filename.substring(extnSeparatorIndex + 1);
}
// String uploadFileExt = file.getAbsolutePath();
InputStream fileUploaded = new FileInputStream(file.getAbsolutePath());
System.out.println("extension: " + uploadFileExt);
String returnStatus= PasswordExcelRead.excelFileScanner(fileUploaded, uploadFileExt);
System.out.println("Final: " + returnStatus);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
通常,您会捕获EncryptedDocumentException
以检查文件是否受密码保护:
InputStream input = ...
Workbook wb;
try {
wb = WorkbookFactory.create(input)
} catch (EncryptedDocumentException e) {
// password protected
}