java - 使用java生成excel并在excel中创建宏

标签 java excel vba outlook apache-poi

我有一个 java 代码,它从 MongoDB 获取数据,然后使用 Apache POI 以格式化方式创建包含此数据的 excel(.xls)。

我的最终要求是将 Excel 工作表中的最后一个工作表邮寄到一组邮件 ID。我无法使用 Java 邮件 API 来执行此操作,因为不会向我提供邮箱的 SMTP 详细信息。 截至目前,我计划在生成的 Excel 中创建一个宏来发送数据。我创建的用于发送邮件的宏是:

Sub Send_Selection_Or_ActiveSheet_with_MailEnvelope()
'Working in Excel 2002-2016
    Dim Sendrng As Range

    On Error GoTo StopMacro

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    'Note: if the selection is one cell it will send the whole worksheet
    Set Sendrng = Selection

    'Create the mail and send it
    With Sendrng

        ActiveWorkbook.EnvelopeVisible = True
        With .Parent.MailEnvelope

            ' Set the optional introduction field thats adds
            ' some header text to the email body.
            .Introduction = "This is a test mail."

            With .Item
                .To = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e1e9e5e6e1fce0e1e6f8fae9e3e9fbe0c8efe5e9e1e4a6ebe7e5" rel="noreferrer noopener nofollow">[email protected]</a>"
                .Subject = "My subject"
                .Send
            End With

        End With
    End With

StopMacro:
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    ActiveWorkbook.EnvelopeVisible = False

End Sub

但是我不知道如何使用java创建这个宏。

最佳答案

OP 询问如何使用包含宏的 Apache POI 库创建 Excel 工作表。不幸的是:这是不可能的。

引用 POI limitations :

Macros can not be created. The are currently no plans to support macros.

幸运的是,它还在继续:

However, reading and re-writing files containing macros will safely preserve the macros.

那么,可以解决什么问题:

  • 您使用 Excel“手动”创建一个 Excel 工作表,其中包含您的宏
  • 您使用 POI 将数据添加到此类现有工作表
  • 将“一起”保存到新工作表中

(或某种变体,例如创建空模板,复制该模板,然后打开/更新其中一个副本)

关于java - 使用java生成excel并在excel中创建宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55044117/

相关文章:

vba - 用户表单 QueryClose 只能工作一次

excel - 运行时错误 '9' : Subscript out of range

excel - 如何使用 VBA 获取前五篇新闻文章的名称和链接

vba - 列格式转换为数字,但显示为文本

vba - 为什么我收到需要对象错误(VBA、Excel)

java - 如何从其他布局 Android 中 getText()

java - 在 Robotium Script 中用预期结果验证多个单词

java - 运行 Servlet 时出现 RuntimeException : Tomcat restarting on its own

java - 是否可以将非最终变量传递给匿名类的方法?

excel - 根据列表框选择从表中删除行