Detect if a XLS Excel file contains a macro (using POI)Tag(s): IO
The Apache POI library is required.
FIrst, we define a POIFSReaderListener, called MacroListener, to analyze a given XLS and record if a macro is found.
import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent;
import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener;
public class MacroListener implements POIFSReaderListener {
  boolean macroDetected;
  public boolean isMacroDetected() {
    return macroDetected;
  }
  public void processPOIFSReaderEvent(POIFSReaderEvent event) {
    if(event.getPath().toString().startsWith("\\Macros")
          || event.getPath().toString().startsWith("\\_VBA")) {
      macroDetected = true;
    }
  }
}
To use it, create a POIFSReader and register our MacroListener.
import java.io.FileInputStream;
import org.apache.poi.poifs.eventfilesystem.POIFSReader;
public class DetectXLSMacro {
  private DetectXLSMacro () {}
  public static void main(String[] args) throws Exception{
    System.out.println ("Checking " + args[0]);
    POIFSReader r = new POIFSReader();
    MacroListener ml = new MacroListener();
    r.registerListener(ml);
    FileInputStream fis = new FileInputStream(args[0]);
    r.read(fis);
    System.out.println (ml.isMacroDetected());
    System.out.println ("Done ");
    System.exit(ml.isMacroDetected()? 1 : 0);
  }
 }
 /*
   output
   >java DetectXLSMacro womacro.xls
    Checking womacro.xls
    false
    Done
   >java DetectXLSMacro wmacro.xls
    Checking womacro.xls
    true
    Done
*/
  mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com
