I have :
Macro named "process" that does all the processing work for my worksheets.
I want my Java code that uses Apache POI, to call this macro so that it can process the sheets for me.
How can I call a Macro in Apache POI in Java ?
:: Note ::
I am using
import org.apache.poi.ss.usermodel
in Apache POI.Please, give sample code. (I am new to Apache POI and Java itself.)
Using GcExcel Java, users can load and save Excel files containing macros (. xlsm files) without any issues. Please note that GcExcel Java will not execute these macros. Typically, this feature allows users to load and save the macro-enabled spreadsheets.
I don't think this is possible. POI is a library to read/edit Office files, macros are a whole other beast. You would have to implement a Visual Basic for Applications Interpreter into POI to accomplish this. Macros that are already in your Excel workbook are preserved, but you cannot add new ones or call existing ones.
You can use other tool like com4j. I created a POC just today and works like a charm. Just follow these steps:
With the code generated by tlbimp (it is just a part of com4j), create a small app and write a code like:
// Starts excel and open an existing workbook
_Application app = ClassFactory.createApplication();
app.setVisible(0, true);
_Workbook wb = app.getWorkbooks().open("c:\\test.xlsx", null, null, null, null, null, null, null,
null, null, null, null, null, null, null, 0);
// run a macro
Variant macro = new Variant(Variant.Type.VT_BSTR);
macro.set("my_macro");
wb.getApplication().run(macro, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null);
// Save the excel file and quit
Variant saveBeforeExit = new Variant(Variant.Type.VT_BOOL);
saveBeforeExit.set(1);
wb.close(saveBeforeExit, Variant.getMissing(), Variant.getMissing(), 0);
app.quit();
Further examples: com4j tutorials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With