bateC
bateC

Reputation: 61

Unable to Append R data frame into existing Excel without overwriting

I am a beginner and am trying to simply insert an R data frame from RStudio into an existing Excel sheet without losing previous data in that sheet or overwriting the whole file, eg. insert new data frame (15 rows, 4 columns) in file "Reporting.xlsx" in Sheet "August" from row 16, column 1, so that the previous info is not lost ?

Thank you !

Upvotes: 6

Views: 4805

Answers (2)

eipi10
eipi10

Reputation: 93761

Something like this:

library(openxlsx)
library(dplyr)

# Get existing data and append new data
dat = readWorkbook("Reporting.xlsx", sheet="August")
dat = bind_rows(dat, new_data_frame)

# Write updated data frame to existing worksheet
wb = loadWorkbook("Reporting.xlsx")
writeData(wb, "August", dat)

# Save file (with new name for testing purposes)
saveWorkbook(wb, "Reporting_test.xlsx")

# To overwrite the pre-existing data file, you can do the following (commented out for safety)
#saveWorkbook(wb, "Reporting.xlsx", overwrite=TRUE)

Upvotes: 7

jeron
jeron

Reputation: 92

What I would suggest is importing the Excel file into R Studio, create a new data frame by merging the R data frame and Excel data frame, and then exporting the file.

Upvotes: 3

Related Questions