java:apache_poi_check_if_file_contains_macros

Apache POI Check if File Contains Macros

This code should work for all office file. In this code, we test the file 1.doc in the project root directory. Requirement: POI 3.15 or above.

import org.apache.poi.poifs.macros.VBAMacroReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class Main {
    private static boolean hasVBA(InputStream inputStream) throws IOException {
        boolean returnVal = false;
        VBAMacroReader vbaMacroReader = null;
        try {
            vbaMacroReader = new VBAMacroReader(inputStream);
            Map<String, String> map = vbaMacroReader.readMacros();
            returnVal = true;
        } catch (IOException e) {
            if (!e.getMessage().equals("No VBA project found")) {
                throw e;
            }
        } finally {
            if (vbaMacroReader != null) {
                vbaMacroReader.close();
            }
        }
        return returnVal;
    }

    public static void main(String[] args) throws Exception {
        File file = new File("./1.doc");
        InputStream inputStream = new FileInputStream(file);
        if (hasVBA(inputStream)) {
            System.out.println("This file has VBA");
        } else {
            System.out.println("Нет VBA");
        }
        inputStream.close();
    }
}
  • java/apache_poi_check_if_file_contains_macros.txt
  • Last modified: 2019/02/14 12:32
  • by chongtin