How to Get Macro Information From Word and Excel in Java
Retrieve information about the macros defined in a Microsoft Word or Excel document.
Join the DZone community and get the full member experience.Join For Free
According to the Microsoft website, a macro is a series of commands that you can use to automate a repeated task and can be run when you must perform the task. The use of macro instructions was originally initiated for assembly language programming to perform two main purposes: to reduce the amount of coding that had to be written by generating several assembly language statements from one macro instruction, and to enforce program writing standards.
Nowadays, macros are used for a wide variety of purposes and industries; Microsoft applications currently use Visual Basic for Applications (VBA) programming language to build their macros, and they allow you to choose whether you want to enable or disable existing macros from use. However, when Microsoft was first designing macro features for the Microsoft Office suite, they weren’t thinking about potential internet security risks.
Current versions of the applications do have some security features, but due to the increased presence of predators in cyberspace and the widespread use of online documents, macros that are already present in a file run the risk of having pre-built malicious macros embedded in their code. These infected macros could potentially run arbitrary commands or delete files on your hard drive, wreaking havoc within your computer.
To assist with the protection of your documents, the following APIs can be used in Java to identify macro information in Word or Excel files and let you decide if the commands are safe to enable.
Before we start on either of the APIs, we will need to install the Maven SDK by adding a reference to the repository:
And add a reference to the dependency:
Now, we are ready to begin with our first API, which will return VBA information from a DOCX/DOCM document. The only inputs you need to provide for the following code are the file itself and the API key (this can be retrieved for free on the Cloudmersive website if you don’t have one already).
The result will let you know if the operation was successful, as well as whether or not the document contains VBA macros. To retrieve macro information from an Excel document, it is a similar process and result, with a different function call:
With the returned result, you can eliminate any worries that a macro may be hiding in a document without your knowledge. If the macros detected are safe, you can then choose to enable macros within the file.
Opinions expressed by DZone contributors are their own.