R: Append a worksheet to an excel workbook without reading the entire workbook

一曲冷凌霜 提交于 2020-02-05 08:25:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49181980/r-append-a-worksheet-to-an-excel-workbook-without-reading-the-entire-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!