Search code examples
rexcelreadxl

Write single cell of Excel file from R


readxl makes reading from Excel into R easy: read_excel('test.xlsx',range = 'E2',col_names = FALSE)

But the equivalent write command doesn't exist, right? write_excel('test.xlsx',range = 'E2','What I want to put in the cell',col_names = FALSE)

Does anyone know a way to write a single cell?

Backstory: The Excel file came from someone else and has a bunch of formatting that I don't want to mess with. I just want to insert a new value in one cell. [This is the minimum working example, the actual problem is more difficult. But if I can make it work for a single cell, I'll be able to make it work for my needs.]


Solution

  • As already suggested by @r2evans the openxlsx allows you to write a single value to an excel file via openxlsx::writeData, e.g. the following code writes a single value to cell "B2":

    openxlsx::writeData(wb, sheet = "mysheet", data.frame(value ="My Value"),
                        startCol = "B", startRow = 2, colNames = FALSE)
    

    As the following reproducible example shows writeData also keeps any formatting of an already existing file:

    library(openxlsx)
    
    # Create a workbook
    wb <- createWorkbook()
    addWorksheet(wb, "mysheet")
    
    # Write one value to B2
    writeData(wb, sheet = "mysheet", data.frame(value ="My Value"),
              startCol = "B", startRow = 2, colNames = FALSE)
    # Add some styles
    addStyle(wb, sheet = "mysheet", rows = 2, cols = "B", 
             style = createStyle(textDecoration = "Bold", fgFill = "yellow"))
    saveWorkbook(wb, "myxl.xlsx", overwrite = TRUE)
    
    # Reopen the xl file and write a new value to B2 to check that formatting is retained
    wb <- loadWorkbook("myxl.xlsx")
    writeData(wb, sheet = "mysheet", data.frame(value = "My new Value"),
              startRow = 2, startCol = "B", colNames = FALSE)
    saveWorkbook(wb, "myxl1.xlsx", overwrite = TRUE)