使用Kable for CSS时表格的网格线未显示在邮件中

时间:2019-05-30 10:01:30

标签: r kable kableextra sendmailr

我正在尝试通过mailR发送邮件,并且工作正常。我有一个数据框,我想对特定单元格进行颜色编码。我使用Kable()进行格式化,并获得了所需的输出,它显示了在Rstudio浏览器中应采用的方式。但是在通过邮件发送HTML时,网格线不可见。

我尝试在kable_styling()中添加'bordered'

#color coding for a data frame
library(knitr)
library(kableExtra)

library(dplyr)

a<-mtcars[1:10, 1:2] %>%
        mutate(
                car = row.names(.),
                mpg = cell_spec(mpg, "html", color = ifelse(mpg > 20,                     "red", "blue")),
                cyl = cell_spec(cyl, "html", color = "white", align = "c", angle = 45, 
                                background = factor(cyl, c(4, 6, 8), 
                                                    c("#666666",     "#999999", "#BBBBBB")))
        ) %>%
        select(car, mpg, cyl) %>%
        kable(format = "html", escape = F) %>%
        kable_styling(c("striped","bordered"), full_width = F)


#=================Send Email
library(mailR)
body_B <- paste("<p>
                ",a,"
                <br> Note: report

                <p>",sep="")


Subject <- paste(Sys.Date(), 'xyz',sep= ":")

send.mail(from = "asdf@gmail.com", 
          to = c("asdf@gmail.com"),
          subject = Subject,        
          body = body_B,
          html = TRUE,
          smtp = list(host.name = "smtp.gmail.com", port = 587,
                      user.name = "#####",
                      passwd = "#####", ssl = T), 
          authenticate = T,
          #attach.files = raw_data,
          send = TRUE)

1 个答案:

答案 0 :(得分:0)

打印a时,您使用的是print.kableExtra方法,但是body_B没有kableExtra类,因此您将使用默认值为您的消息生成正文的方法。如果您将源代码读到kableExtra:::print.kableExtra,您会发现它确实做了很多操作,然后才将对象发送到浏览器,因此您需要对其进行复制。

这是一种尝试。这可能不是最简单的方法,但是会生成一个可以正确显示的文件:

# Generate an HTML header
html_header <- htmltools::tags$head(rmarkdown::html_dependency_jquery(), 
                                    rmarkdown::html_dependency_bootstrap(theme = "simplex"), 
                                    html_dependency_kePrint())
# Declare body_B to be HTML
html_table <- htmltools::HTML(body_B)

# Glue the two parts together
html_result <- htmltools::tagList(html_header, html_table)

# Create a temp file and write the result there
html_file <- tempfile(fileext = ".html")
htmltools::save_html(html_result, file = html_file, background = "white")

# That will require several different files.  You probably want to 
# merge them all into one to display.  Pandoc can do that...
system(paste(rmarkdown::pandoc_exec(), "--self-contained --template", html_file, "-o", html_file, "</dev/null"))

# The result is now in the file named in html_file.  If you want it as
# a character variable, you can read it.
html_lines <- readLines(html_file)

我没有尝试将其放入电子邮件中,但是我不明白为什么它不起作用。