Как узнать, что Excel защищен паролем или нет - PullRequest
0 голосов
/ 12 июня 2018

Как определить, что файл excel (xls и xlsx) защищен паролем?есть ли флаг для проверки?Примечание. Существует два типа паролей для Excel (xls / xlsx):

  1. Защищен паролем (Excel-> Сохранить как-> Инструменты-> Общая опция)
  2. Парользашифрованный (excel-> File permissin-> encrypt)

Мой код работает только для xls с зашифрованным паролем.

  1. xls encrypted-EncryptedDocumentException -pass (правильное исключение)
  2. xls защищен паролем -IllegalArgumentException-fail (общее исключение)
  3. xlsx зашифрован-POIXMLException-fail (общее исключение)
  4. xlsx защищен паролем -POIXMLException-fail (общее исключение)

Для вышеперечисленных неудачных случаев вместо общего исключения я хочу улучшить этот код.

Используемые банки:

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

1 Ответ

0 голосов
/ 12 июня 2018

Обычно вы ловите EncryptedDocumentException, чтобы проверить, защищен ли файл паролем:

InputStream input = ...
Workbook wb;
try {
    wb = WorkbookFactory.create(input)
} catch (EncryptedDocumentException e) {
   // password protected
}
...