我有一个 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/