【发布时间】:2017-03-09 15:43:15
【问题描述】:
我正在使用 xlsx 包创建格式有些复杂的 Excel 工作表。
问题是当我已经格式化了一个单元格并想在其上添加一些内容时——然后格式会恢复为默认值,除了我要添加的新内容。
一种解决方案是指定每种不同的大小写并对其应用完整的格式。一张大单,具体案例的数量可能会失控。
我猜肯定有办法逐步添加格式,但在文档中还没有找到任何关于它的内容。
我当前做事方式的可重现示例:
require(xlsx)
# Some random data
n <- 20L
set.seed(1L)
df <- data.frame(species = sample(c("Cat", "Dog", "Unkown"), n, replace = TRUE),
speed = abs(rnorm(n)) * 20L)
# Create workbook
dfwb <- createWorkbook(type = "xlsx")
sheet <- createSheet(dfwb, sheetName = "ani")
addDataFrame(df, sheet, startRow = 1, startColumn = 1, row.names = FALSE)
# Change text of Cat to "red"
row <- getRows(sheet, rowIndex = which(df[, "species"] == "Cat") + 1L)
cel <- getCells(row, colIndex = 1)
redh_style <- CellStyle(dfwb) + Font(dfwb, color = "red")
for (i in names(cel)) {
setCellStyle(cel[[i]], redh_style)
}
# Highlight all rows where speed exceeds 18
row <- getRows(sheet, rowIndex = which(df[, "speed"] > 18) + 1L)
cel <- getCells(row, colIndex = 1:2)
high_style <- CellStyle(dfwb) + Fill(foregroundColor="#E2E6EB")
for (i in names(cel)) {
setCellStyle(cel[[i]], high_style)
}
# Save
setwd("c:/temp/csvm/")
saveWorkbook(dfwb, "so_cat.xlsx")
最后,一些以前的红色字体变回黑色了。
附言。我尝试过其他软件包,但想坚持使用xlsx。
XLConnect 不允许直接从 R 进行某些类型的格式化,我在运行 openxlsx 时遇到了一些技术困难。
【问题讨论】: