如何将R数据框保存到Excel文件中,某些单元格以粗体显示?

时间:2016-08-01 01:17:51

标签: r excel xlsx xlconnect

我经常用相关矩阵写论文。我希望能够以xls或xlsx格式将相关矩阵导出到Excel。我还想格式化满足阈值的粗体相关(例如,> .2)。我想也许XLConnect可能提供功能。

为了使示例简单,假设数据框如下,并假设我想加粗大于5的所有单元格。

x <- data.frame(matrix(1:9, nrow = 3))
# > x
#   X1 X2 X3
# 1  1  4  7
# 2  2  5  8
# 3  3  6  9

顺便说一句,我注意到已经提出了用于降价的单元格的解决方案:

我也找到了这个答案,但它不是一个非常通用的解决方案,因为它需要相当多的时间来适应采用数据框和格式化规则的一般任务:

export data frames to Excel via xlsx with conditional formatting

1 个答案:

答案 0 :(得分:3)

我创建了以下根据@jota's answer here

改编的功能
xlsx_boldcells <- function(x, matches, file = "test.xlsx", sheetname = "sheet1") {
    # x data.frame or matrix
    # matches: logical data.frame or matrix of the same size indicating which cells to bold
    # copy data frame to work book and load workbook
    require(xlsx)
    write.xlsx(x, file, sheetName=sheetname)
    wb <- loadWorkbook(file)              

    # specify conditional formatting
    # Note: this could be modified to apply different formatting
    # see ?CellStyle
    fo <- Font(wb, isBold = TRUE)  
    cs <- CellStyle(wb, font=fo)  

    # Get cell references
    sheets <- getSheets(wb)               # get all sheets
    sheet <- sheets[[sheetname]]          # get specific sheet
    rows <- getRows(sheet, rowIndex=2:(nrow(x)+1))  # get rows
    cells <- getCells(rows, colIndex = 2:(ncol(x)+1))  

    # Matches to indexes
    indm <- data.frame(which(matches, arr.ind = TRUE, useNames = FALSE)) 
    names(indm) <- c("row", "col")
    # +1 required because row and column names occupy first rows and columns
    indm$index <- paste(indm$row + 1, indm$col + 1, sep = ".")

    # apply cell style
    lapply(indm$index, function(ii) setCellStyle(cells[[ii]],cs))

    # save workbook
    saveWorkbook(wb, file)
}

因此,它可以应用于提出的问题:

 xlsx_boldcells(x, x > 5)

得到以下特性:

excel sheet with bold

或者它可以应用于公共相关问题(即,加粗大相关,例如,大于.6),如下所示:

data(mtcars)
cors <- round(cor(mtcars), 2)
xlsx_boldcells(cors, abs(cors) > .6 & cors!=1, file = "cormatrix.xlsx")

bold cell formatted correlations using xlsx