Unable to Append R data frame into existing Excel

2019-08-08 00:05发布

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 !

2条回答
手持菜刀,她持情操
2楼-- · 2019-08-08 00:27

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.

查看更多
小情绪 Triste *
3楼-- · 2019-08-08 00:34

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)
查看更多
登录 后发表回答