【问题标题】:How to create a row in a Excel sheet from R?如何从 R 在 Excel 工作表中创建一行?
【发布时间】:2017-07-23 06:23:05
【问题描述】:

我正在尝试使用 R 在我的 Excel 文件的每张纸上添加一个标题(因为我的所有数据都来自 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) 设置单元格值。

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

# 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个表;例如,此功能似乎没有将表格保存在第二行的选项。

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

【问题讨论】:

    标签: r excel xlsx


    【解决方案1】:

    我认为您有多种选择:

    • 保存数据时可以在addDataFrame()函数中使用参数startRow=2
    • 您可以在将标题放在第 1 行之前使用 rows &lt;-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")
    

    【讨论】:

    • 您好弗洛里安,感谢您的回答。不幸的是,在放置标题之前使用 createRow 函数不起作用。我将不得不手动执行此操作,您的第一个选项是 addDataFrame() 中的 startRow=2。
    猜你喜欢
    • 2020-08-19
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2018-05-13
    • 2016-05-26
    相关资源
    最近更新 更多