简体   繁体   English

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

[英]Generate a excel using java and create a macro in the excel

I have a java code that takes data from MongoDB and later creates an excel(.xls) containing this data using Apache POI but in a formatted manner.我有一个 java 代码,它从 MongoDB 获取数据,然后使用 Apache POI 创建一个包含此数据的 excel(.xls),但以格式化的方式。

My final requirement is to mail the last worksheet inside the excel sheet to a set of mail ID's.我的最终要求是将 Excel 工作表中的最后一个工作表邮寄到一组邮件 ID。 I cannot use the Java mail API to do that since the SMTP details of the mailbox will not be provided to me.我无法使用 Java 邮件 API 来执行此操作,因为不会向我提供邮箱的 SMTP 详细信息。 As of now I am planning to create a macro inside the generated excel to send the data.截至目前,我计划在生成的 excel 中创建一个宏来发送数据。 The macro I have created to send mail is:我创建的用于发送邮件的宏是:

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 = "iamnithinprakash@gmail.com"
                .Subject = "My subject"
                .Send
            End With

        End With
    End With

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

End Sub

But I don't know how to create this macro using java.但我不知道如何使用 java 创建这个宏。

The OP asks how to create Excel sheet using the Apache POI library that include macros. OP 询问如何使用包含宏的 Apache POI 库创建 Excel 工作表。 Unfortunately: that is not possible.不幸的是:这是不可能的。

Quoting the POI limitations :引用 POI 限制

Macros can not be created.无法创建宏。 The are currently no plans to support macros.目前没有计划支持宏。

Luckily, it continues:幸运的是,它继续:

However, reading and re-writing files containing macros will safely preserve the macros.但是,读取和重写包含宏的文件将安全地保留宏。

So, what could work out:那么,什么可以解决:

  • you create an empty Excel sheet "manually", with Excel, that includes your macro您使用 Excel“手动”创建一个空的Excel 工作表,其中包含您的宏
  • you use POI to add the data to such an existing sheet您使用 POI数据添加到此类现有工作表中
  • you save that "together" into a new sheet你把那个“一起”保存到一个新的工作表中

(or some variation of that, like creating that empty template, copy that, and open/update one of the copies) (或者它的一些变体,比如创建那个空模板,复制它,然后打开/更新其中一个副本)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM