如何在R生成的邮件HTML表格中为指定值设置单元格颜色?
实现HTML表格单元格条件着色并发送邮件(R语言)
需求说明
现有使用mailR和htmlTable发送带HTML表格邮件的代码,需要给表格单元格添加条件背景色:
- 值为110的单元格:绿色背景
- 值为3的单元格:红色背景
- 其余单元格:黄色背景
解决方案
核心思路是给目标单元格添加自定义CSS类,再通过CSS样式定义对应背景色,具体修改如下:
- 生成单元格样式类矩阵
先根据数据值创建一个和数据维度一致的矩阵,给不同值的单元格分配对应的CSS类:
x <- head(mtcars) # 创建样式类矩阵 cell_classes <- matrix( apply(x, 1:2, function(val) { if (val == 110) "green-bg" else if (val == 3) "red-bg" else "yellow-bg" }), nrow = nrow(x) )
- 修改
htmlTable调用,传入样式类
在生成HTML表格时,通过css.class参数传入上面的矩阵:
y <- htmlTable(x, rnames = FALSE, css.class = cell_classes)
- 更新CSS样式定义
在<style>标签里添加三个自定义类的背景色样式,同时保留原有的表格边框等样式:
<style> body{font-family:Calibri, sans-serif;} table{border-left:1px solid #000000;border-top:1px solid #000000;} table th{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:bold; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;} table td{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:normal; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;} /* 新增条件背景色样式 */ .green-bg {background-color: #90EE90;} .red-bg {background-color: #FF6347;} .yellow-bg {background-color: #FFFFE0;} </style>
完整修改后的代码
library(mailR) library(htmlTable) x <- head(mtcars) # 创建单元格样式类矩阵 cell_classes <- matrix( apply(x, 1:2, function(val) { if (val == 110) "green-bg" else if (val == 3) "red-bg" else "yellow-bg" }), nrow = nrow(x) ) # 生成带样式类的HTML表格 y <- htmlTable(x, rnames = FALSE, css.class = cell_classes) html_body <- paste0("<html><head> <style> body{font-family:Calibri, sans-serif;} table{border-left:1px solid #000000;border-top:1px solid #000000;} table th{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:bold; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;} table td{border-right:1px solid #000000;border-bottom:1px solid #000000;font-size:13px; font-weight:normal; margin: 0px; padding-left: 5px; padding-right: 5px; margin: 0px;} /* 条件背景色样式 */ .green-bg {background-color: #90EE90;} .red-bg {background-color: #FF6347;} .yellow-bg {background-color: #FFFFE0;} </style> </head><body><p> This is a test email. Ignore it.</p>", y, "</body></html>") sender <- "SENDER@gmail.com" recipients <- c("RECIPIENTS@gmail.com") send.mail(from = sender, to = recipients, subject = "Test Email", body = html_body, smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "USERNAME@gmail.com", passwd = "PASSWORD", ssl = TRUE), authenticate = TRUE, html = TRUE, send = TRUE)
说明
- 颜色值用了常见的浅绿、浅红、浅黄色,你可以根据需求替换为十六进制颜色码或颜色名称
apply(x, 1:2, ...)会遍历矩阵的每个元素,精准判断每个单元格的值并分配样式类htmlTable的css.class参数接受和数据同维度的矩阵,实现单元格级别的样式控制
内容的提问来源于stack exchange,提问作者sai
相关产品推荐
相关产品推荐

