我基本上是从这个问题和我的答案中复制代码, 并针对这个用例进行一些调整。我不确定这方面的礼仪,但我只是想表明这是可以做到的!任何人,让我知道我是否做了一些我不应该做的事情来重用链接问题中的代码来回答这个问题。如果在回答了另一个问题后这被视为重复,那我很好。只是想帮忙!
首先,稍微重新格式化数据。
# split the X column so there will be one numeric entry per cell
d <- matrix(as.numeric(unlist(strsplit(as.character(Data$X), ";"))),
ncol = 20, byrow = TRUE)
d <- data.frame(d, Data$Y)
cols <- length(d[1, ]) # number of columns, we'll use this later
其次,我们可以使用函数 inxlsx
创建一个工作簿,然后获取单元格值。
library(xlsx)
# exporting data.frame to excel is easy with xlsx package
sheetname <- "mysheet"
write.xlsx(d, "mydata.xlsx", sheetName=sheetname)
file <- "mydata.xlsx"
# but we want to highlight cells if value greater than or equal to 5
wb <- loadWorkbook(file) # load workbook
fo1 <- Fill(foregroundColor="blue") # create fill object # 1
cs1 <- CellStyle(wb, fill=fo1) # create cell style # 1
fo2 <- Fill(foregroundColor="red") # create fill object # 2
cs2 <- CellStyle(wb, fill=fo2) # create cell style # 2
sheets <- getSheets(wb) # get all sheets
sheet <- sheets[[sheetname]] # get specific sheet
rows <- getRows(sheet, rowIndex=2:(nrow(d)+1)) # get rows
# 1st row is headers
cells <- getCells(rows, colIndex = 2:cols) # get cells
# in the wb I import with loadWorkbook, numeric data starts in column 2
# The first column is row numbers. The last column is "yes" and "no" entries, so
# we do not include them, thus we use colIndex = 2:cols
values <- lapply(cells, getCellValue) # extract the cell values
接下来我们找到需要根据标准进行格式化的单元格。
# find cells meeting conditional criteria > 5
highlightblue <- NULL
for (i in names(values)) {
x <- as.numeric(values[i])
if (x > 5 && !is.na(x)) {
highlightblue <- c(highlightblue, i)
}
}
# find cells meeting conditional criteria < 5
highlightred <- NULL
for (i in names(values)) {
x <- as.numeric(values[i])
if (x < 5 && !is.na(x)) {
highlightred <- c(highlightred, i)
}
}
最后,应用格式并保存工作簿。
lapply(names(cells[highlightblue]),
function(ii) setCellStyle(cells[[ii]], cs1))
lapply(names(cells[highlightred]),
function(ii) setCellStyle(cells[[ii]], cs2))
saveWorkbook(wb, file)