I have a 26 mb excel workbook to which I am trying to add a 42 kb worksheet. Using the openxlsx package, I have the following code:
wb_object <- loadWorkbook(to_name2) addWorksheet(wb_object, "New Data") writeData(wb_object, sheet = "New Data", m_data) saveWorkbook(wb_object, to_name2, overwrite = TRUE)
What I have noticed is that this code takes about 2 minutes to execute. I believe R is reading in the entire 26 mb file and then appending the 42 kb worksheet. Is there any way to append the 42 kb worksheet to the 26 mb workbook without having to read in the 26 mb file? Would save 2 minutes per run.
I generally use
openxlsx, but I’m not sure if
openxlsx has a way to add a worksheet to an Excel file without first loading the Excel workbook into R. However, with the
xlsx package, you can add a new worksheet without loading the Excel file. For example, if your file is “test.xlsx”, then you could do:
library(xlsx) write.xlsx(new_data, "test.xlsx", sheetName="New_Sheet", append=TRUE)
If I need to save anything in an Excel file, I generally try to do everything in R and then write whatever needs to go into the Excel file at the end. However, if you need to add to an existing Excel file, the above code provides an option to do that.