如何从 Java 代码调用 Excel VBA 宏?
我需要通过 Java 从数据库获取的数据生成 Excel 工作表。 为此,我需要在生成 Excel 时调用一些 VBA 宏函数。 谁能帮助我如何从 Java 代码调用 VBA 宏?
I need to generate an Excel sheet from the data fetched from a database through Java.
For that, I need to call some VBA Macro functions while generating that Excel.
Can anybody help me with how to call VBA Macro from Java code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不太了解您从数据库中的数据生成 Excel 工作表的总体方法。通常,我会按照 Vivek 的建议使用 Apache POI。
但是,如果您确实需要在工作表中调用 Excel 宏,那么您需要两件事:
首先,您需要一个 JAVA 到 COM 的桥接器,例如 JACOB、COM4J 或类似工具。如果它支持自动化接口就足够了。它不需要有完整的 COM 支持。
其次,使用 JAVA-to-COM 桥接器,您应该启动 Excel、加载 Excel 工作表、运行宏、保存并关闭 Excel。所以你必须调用相当于:
I don't really understand your overall approach to generate Excel sheet from the data in a database. Normally, I'd use Apache POI as proposed by Vivek.
However, if you really need to call an Excel macro in a sheet, then you need two things:
First, you need a JAVA-to-COM bridge like JACOB, COM4J or a similar tool. It is sufficient if it supports automation interfaces. It doesn't need to have full COM support.
Second, using the JAVA-to-COM bridge, you should start Excel, load the Excel sheet, run the macro, save it and close Excel. So you have to call the equivalent of:
如果您无法使用
JACOB
或COM4J
,您可以创建一个 Visual Basic 脚本并从 Java 程序运行该脚本。要创建脚本,请打开记事本并编写如下内容:
将其另存为
myVBS.vbs
并且您可以从 Java 代码中这样调用它:If you can't use
JACOB
orCOM4J
you can make a Visual Basic Script and run the script from your Java program.To create the script open notepad and write something like this:
Save it as
myVBS.vbs
and you can call it like this from your Java code:当工作表更改时,您还可以在 Excel 中捕获事件,您甚至可以调用您想要的任何宏,因此,如果您想调用宏“蓝色”,您可以在隐藏的工作表中写入“蓝色”,然后Excel 将捕获更改,当您捕获更改时,您可以看到写入的内容并执行一些 if ifelse 语句以获取您想要为该实例调用的宏。不是很好的编码,但是一个简单的解决方法。不过我会自己做其他方法。
You might also be able to capture an event in excel when a worksheet changes you can have the even call whatever macro you want it to, so if you want to call the macro "Blue" you can write "blue" in a hidden worksheet then Excel will capture the change, when you capture the change you can see what was written and do some if ifelse statements to get to the macro you want to call for that instance. Not really good coding, but an easy workaround. I would do the other methods myself though.
对我有用的解决方案:
java代码:
myVBS.vbs脚本:
solution that works for me:
java code:
myVBS.vbs script:
我不确定是否可以直接从 Java 调用宏。但您可以将数据填充到 Excel 工作表和表格中。当用户第一次打开 Excel 工作表时调用宏。您可以使用 Apache POI 工具在包含宏的 Excel 工作表中填充数据 - http://poi .apache.org/spreadsheet/index.html
I am not sure if it is possible to call macro directly from Java. But you can populate the data in excel sheet & call the macro when the user opens the excel sheet for the first time. You would be able to populate data in a excel sheet containing macros using Apache POI tool - http://poi.apache.org/spreadsheet/index.html