rdataframeopenxlsx

Format dataframe to Excel using openxlsx


Any suggestion how can i deal with the two first rows? My data frame actually is just the second row (which has the title of the columns) to the bottom. But i don't have any idea how to add the first line

example

I've tried to pack two data frames:

addWorksheet(wb, "sheet2")
auxdata = tibble(`TEST` = rep('',nrow(base_original)))

writeData(wb, sheet = 3, x = auxdata)
writeData(wb, sheet = 3, x = df1)

but didn't work of course


Solution

  • writeData has a startRow (and startCol) argument to specify the region to write the data. Hence, you can set startRow=2 to write your dataset. Then add the additional header line in the first row:

    library(openxlsx)
    
    fn <- tempfile(".xlsx")
    df1 <- mtcars[, 1:2]
    
    wb <- createWorkbook()
    addWorksheet(wb, "sheet2")
    writeData(wb, sheet = "sheet2", x = "TEST")
    writeData(wb, sheet = "sheet2", x = df1, startRow = 2)
    mergeCells(wb, sheet = "sheet2", cols = 1:2, rows = 1)
    
    saveWorkbook(wb, fn)
    

    enter image description here