[英]How do you move an Excel worksheet from one workbook into another using openxlsx in R?
I am trying to take input from 3 separate Excel files, do some work with them in R, and return all three Excel files, as well as my calculations, as a single Excel file.我试图从 3 个单独的 Excel 文件中获取输入,在 R 中对它们进行一些处理,然后将所有三个 Excel 文件以及我的计算作为单个 Excel 文件返回。 Obviously this can be done manually (and is probably safer that way), but I'd like to automate it if possible.显然,这可以手动完成(这样可能更安全),但如果可能的话,我想将其自动化。
I've been using the openxlsx package, which works really well for reading in a single workbook and then appending the work I've done in R, but I can't figure out how to move sheets from one workbook object to another.我一直在使用 openxlsx 包,它非常适合在单个工作簿中阅读,然后附加我在 R 中完成的工作,但我不知道如何将工作表从一个工作簿对象移动到另一个工作簿对象。 I tried:我试过:
wb1 <- loadWorkbook("hi.xlsx")
wb2 <- loadWorkbook("bye.xlsx")
wb2[[2]] <- wb1[[1]]
And a few other things, but nothing seemed to work.还有其他一些事情,但似乎没有任何效果。 I have noted that:我注意到:
names(wb1)
Will give the names of the worksheets in wb1, but there doesn't seem to be a way to move worksheets around.将在 wb1 中给出工作表的名称,但似乎没有办法移动工作表。 Any ideas?有什么想法吗?
Thanks in advance!提前致谢!
EDIT: Sorry--I should have been more clear.编辑:对不起 - 我应该更清楚。 I want to read in the sheet with all of its original formatting and write it to the new file.我想在工作表中读取其所有原始格式并将其写入新文件。 Using read.xlsx loses all of the formatting.使用 read.xlsx 会丢失所有格式。
Using the xlsx
package:使用xlsx
包:
library(xlsx)
wb1 <- read.xlsx("Workbook1.xlsx", sheetIndex = 1)
wb2 <- read.xlsx("Workbook2.xlsx", sheetIndex = 1)
write.xlsx(wb1, "Workbook Joined.xlsx")
write.xlsx(wb2, "Workbook Joined.xlsx", sheetName = "Sheet2", append = T)
I made it work as follows (mind you: this only works for sheets with data):我按如下方式工作(请注意:这仅适用于带有数据的工作表):
wb1 <- loadWorkbook("hi.xlsx")
wb2 <- loadWorkbook("bye.xlsx")
lapply(sheets(wb2), function(s) {
dt <- read.xlsx("bye.xlsx", sheet = s)
addWorksheet(wb1, sheetName = s)
writeData(wb1, s, dt)
})
Here is an example how to use read.xlsx function to read data from excel files下面是如何使用 read.xlsx 函数从 excel 文件中读取数据的示例
read.xlsx(xlsxFile, sheet = 1, startRow = 1, colNames = TRUE,
rowNames = FALSE, detectDates = FALSE, skipEmptyRows = TRUE,
rows = NULL, cols = NULL, check.names = FALSE, namedRegion = NULL)
sheet indicates The name or index of the sheet to read data from. sheet 指示要从中读取数据的工作表的名称或索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.