2

我有一个 26 mb 的 Excel 工作簿,我正在尝试向其中添加一个 42 kb 的工作表。使用 openxlsx 包,我有以下代码:

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)

我注意到的是这段代码需要大约 2 分钟才能执行。我相信 R 正在读取整个 26 mb 文件,然后附加 42 kb 工作表。有没有办法将 42 kb 工作表附加到 26 mb 工作簿而无需读取 26 mb 文件?每次运行将节省 2 分钟。

4

1 回答 1

2

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.

于 2018-03-08T20:55:25.520 回答