4

我有一个如下所示的数据框。然后我将数据框转换为 html 表。

# Use RDCOMClient to send email from outlook
library(RDCOMClient)
# Use xtable to convert dataframe into html table
library(xtable)

# Create dataframe
df <- as.data.frame(mtcars[1:3,1:3])

# Create HTML object
df_html <- xtable(df)

现在,我正在使用电子邮件线程通过 Outlook 在 R 中发送电子邮件中给出的精彩解决方案从 Outlook 发送电子邮件

## init com api
OutApp <- COMCreate("Outlook.Application")
## create an email 
outMail = OutApp$CreateItem(0)
## configure  email parameter 
outMail[["To"]] = "dest@dest.com"
outMail[["subject"]] = "some subject"
outMail[["body"]] = df_html
## send it                     
outMail$Send()

对于我的电子邮件正文,我想要作为 html 表附加的数据框 df。当我执行上述代码时,我收到以下错误消息。

Error in `[[<-`(`*tmp*`, "body", value = list(mpg = c(21, 21, 22.8), cyl = c(6,  : 
  Can't attach the RDCOMServer package needed to create a generic COM object
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘RDCOMServer’

当我将行更改outMail[["body"]] = df_html为 时outMail[["body"]] = paste0(df_html),我收到了电子邮件,但输出不是表格。在我的展望中如下所示。

c(21, 21, 22.8), c(6, 6, 4), c(160, 160, 108)

我希望这是一张桌子。我怎样才能做到这一点?谢谢!

4

1 回答 1

5

我终于找到了在 Microsoft Outlook 中将数据框粘贴为 HTML 表格的解决方案。这是使用xtable包。部分解决方案的功劳从这里转到@lukeA - How to show an excel worksheet in Outlook body by R

下面是解决方案。

library(RDCOMClient)
library(xtable)

x <- head(mtcars)
y <- print(xtable(x), type="html", print.results=FALSE)

body <- paste0("<html>", y, "</html>")

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"
outMail[["HTMLbody"]] = body
outMail$Send()

这是 Microsoft Outlook 中输出的样子。

来自 Microsoft Outlook 的屏幕截图

于 2017-11-13T13:21:40.860 回答