通过XLConnect从R更改MS Excel文件中的单元格格式

试图通过XLConnectR中的MS Excel表中对单元格进行简单更改。

具体做第一行加粗。 我从快速search中看到的是,你可以在Excel中定义一个样式,然后将其导入到R中,但是这个选项并不适合我,因为我所做的所有更改都必须由R脚本来重现。

以下是使用XLConnect创build的Excel文件的XLConnect

 require(XLConnect) wb <- loadWorkbook("test.xlsx", create = TRUE) createSheet(wb, name = "foo") df <- data.frame(number = 1:4, species = c("dog", "cat")) writeWorksheet(wb, df, sheet = "foo", startRow = 1, startCol = 1) saveWorkbook(wb) 

也许这更容易]与xlsx包? 我已经遇到了openxlsx技术问题。

编辑 :我知道如何更改单元格的背景颜色,并假设类似的方法可以用来将字体更改为粗体:

 cs.tr <- createCellStyle(wb) setFillForegroundColor(cs.tr, color = XLC$"COLOR.WHITE") setCellStyle(wb, sheet = "foo", row = 1, col = 1:2, cellstyle = cs.tr) 

这个问题有一个小的解决方法。 创build一个“模板”Excel电子表格,并创build您感兴趣的单元格样式。例如,在Excel中,我创build了一个名为my.header和my.table的新单元格样式。 my.header是11磅粗体Calibri,我的尺寸是10磅Calibri。 将此Excel文件(“myExcel.xlsx”)保存在有用的地方。

然后在R中,执行以下操作:

 library(XLConnect) wb <- loadWorkbook("myExcel.xlsx") # bring excel styles in the spreadsheet into R style.title <- getCellStyle (wb , "my.header") style.normal <- getCellStyle (wb , "my.table") # copy the first sheet in myExcel as a "template" for use in R sheet_names <- getSheets(wb) sheet_template <- sheet_names[1] # do something useful in R df<-mtcars # now clone template as a new sheet (instead of creating it) cloneSheet(wb, sheet_template, "newSheet") writeWorksheet (wb , data = df , sheet ="newSheet" , startRow =1 , startCol =1 , header = TRUE ) setCellStyle(wb , sheet ="newSheet" , row =1 , col =1:dim(df)[2] , cellstyle =style.title) saveWorkbook ( wb, "myNewExcel.xlsx") 

我克隆电子表格选项卡,以便我也可以将查看缩放设置为我最喜欢的缩放级别…您可能不必这样做。