如何从 R 在 Excel sheet 中创建一行?

How to create a row in a Excel sheet from R?

我正在尝试使用 R 在我的 Excel 文件的每个 sheet 上添加一个标题(因为我的所有数据都来自 R,我需要将其组织在 Excel 文件)。为了做到这一点,我使用了 'xlsx' 包中的这个函数,我发现它 here:

#++++++++++++++++++++++++
# Helper function to add titles
#++++++++++++++++++++++++
# - sheet : sheet object to contain the title
# - rowIndex : numeric value indicating the row to 
#contain the title
# - title : the text to use as title
# - titleStyle : style object to use for title
xlsx.addTitle<-function(sheet, rowIndex, title, titleStyle){
rows <-createRow(sheet,rowIndex=rowIndex)
sheetTitle <-createCell(rows, colIndex=1)
setCellValue(sheetTitle[[1,1]], title)
setCellStyle(sheetTitle[[1,1]], titleStyle)
}

程序是: 1)创建一个新行 2) 在此行中创建一个单元格以包含标题。 3) 设置单元格值。

为了在每个 sheet 上添加一个标题,我把这个函数放在一个循环中:

# preparing for the loop 
wb <- loadWorkbook(file = "tmp_regioes.xlsx")
sheets <- getSheets(wb)
z <- length(titles)

# creating the style
SUB_TITLE_STYLE <- CellStyle(wb) + 
  Font(wb,  heightInPoints=14, 
       isItalic=TRUE, isBold=FALSE)

# loop
for (i in (1:z)) {

  sheet <- sheets[[i]]
  # Add sub title
  xlsx.addTitle(sheet, rowIndex=1, 
                title= paste0(titles[i]),
                titleStyle = SUB_TITLE_STYLE)
}

但它并没有真正创建一个新行;相反,它删除了我第一行的内容,其中包含值(我的表的列名)。

澄清一下,文件 "tmp_regioes.xlsx" 是使用函数 WriteXLS 创建的,因为我需要在同一个文件中保存 10 个表;例如,此功能似乎没有用于保存第二行表格的选项。

如果有人能帮助我,我会很高兴。 提前谢谢大家。

我认为你有多种选择:

  • 保存数据时可以在addDataFrame()函数中使用参数startRow=2
  • 您可以在将标题放在第 1 行之前使用 rows <-createRow(sheet,rowIndex=1)

下面的代码创建了一个示例 xlsx 文件,正如您从头开始提到的那样。希望这对您有所帮助!

library(xlsx)

df = data.frame(a=c(1,2,3),b=c(2,3,4))
titles = c( "A", "B","C")

wb<- createWorkbook(type = "xlsx")
sheets <- getSheets(wb)
z <- length(titles)

# creating the style
SUB_TITLE_STYLE <- CellStyle(wb) + 
  Font(wb,  heightInPoints=14, 
       isItalic=TRUE, isBold=FALSE)

# loop
for (i in (1:z)) {

  createSheet(wb, sheetName=paste0("Sheet",i))
  sheets <- getSheets(wb)
  sheet <- sheets[[i]]
  # Add sub title

  addDataFrame(df, sheet, col.names = TRUE, row.names = FALSE,
               startRow = 1, startColumn = 1)  
  rows <-createRow(sheet,rowIndex=1)
  xlsx.addTitle(sheet, rowIndex=1, 
                title= paste0(titles[i]),
                titleStyle = SUB_TITLE_STYLE)


}

saveWorkbook(wb, "tmp.regioes.xlsx")