xlsx R包会覆盖以前的格式
我正在用xlsx
包创build一个格式有点复杂的Excel工作表。
问题是,当我已经格式化了一个单元格,并且想在其上添加一些内容时 – 除了我添加的新东西之外,格式化将恢复为默认值。
一种解决scheme是指定每个不同的情况,并将完整的格式应用到它。 特定案件的数量可能会随着一张大单子而失控。
我猜想必须有一步一步的添加格式,但还没有发现任何关于它的文档。
我现在做事的一个可重复的例子:
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")
最后,一些以前的红色字体又回到了黑色。
PS。 我已经尝试过其他软件包,但希望坚持使用xlsx
。 XLConnect
不允许直接从R进行某些types的格式化,并且在运行openxlsx
遇到技术困难。
这是一种方法。 主要思想是为每个单元格build立一个并行的格式列表,其中每个列表元素是一个单元格。 这允许您根据需要追加格式化属性。 最后,我们将这个格式列表应用到每个单元格。
首先,我们build立一个空白列表:
# Set up blank list of formats fmts <- list()
现在,我们根据第一个标准进行格式化,将font属性添加到选定单元格的fmts
列表中:
# Change text of Cat to "red" row <- getRows(sheet, rowIndex = which(df[, "species"] == "Cat") + 1L) cel <- getCells(row, colIndex = 1) for (i in names(cel)) { if (i %in% names(fmts)) { fmts[[i]] <- c(fmts[[i]], list(Font(dfwb, color = "red"))) } else { fmts[[i]] <- list(CellStyle(dfwb), Font(dfwb, color = "red")) } }
接下来,做一下背景:
# Highlight all rows where speed exceeds 18 row <- getRows(sheet, rowIndex = which(df[, "speed"] > 18) + 1L) cel <- getCells(row, colIndex = 1:2) for (i in names(cel)) { if (i %in% names(fmts)) { fmts[[i]] <- c(fmts[[i]], list(Fill(foregroundColor="#E2E6EB"))) } else { fmts[[i]] <- list(CellStyle(dfwb), Fill(foregroundColor="#E2E6EB")) } }
当我们检查fmts
,我们注意到一些元素只有两个项目(基本单元格样式,加上字体或背景),而其他元素有三个(基本单元格样式,字体和背景):
str(fmts, m = 1) # List of 16 # $ 2.1 :List of 3 # $ 6.1 :List of 3 # $ 11.1:List of 2 # $ 12.1:List of 3 # $ 13.1:List of 2 # $ 2.2 :List of 2 # $ 5.1 :List of 2 # $ 5.2 :List of 2 # $ 6.2 :List of 2 # $ 9.1 :List of 2 # $ 9.2 :List of 2 # $ 12.2:List of 2 # $ 15.1:List of 2 # $ 15.2:List of 2 # $ 19.1:List of 2 # $ 19.2:List of 2
最后,我们遍历fmts
并应用样式。 Reduce
function非常有用:
# Apply formatting for (i in names(fmts)) { idx <- as.numeric(unlist(strsplit(i, "\\."))) cel <- getCells(getRows(sheet, rowIndex = idx[1]), colIndex = idx[2]) setCellStyle(cel[[i]], Reduce(`+.CellStyle`, fmts[[i]]) ) }
输出: