Not sure why, but I just want to export two different dataframes into one workbook.
I have the below -
A=data.frame(a=1:10)
B=data.frame(a=2:11)
write.xlsx(A,file="A.xlsx",sheetName="sheet_A",append=FALSE)
write.xlsx(B,file="A.xlsx",sheetName="sheet_B",append=TRUE)
The error is when I open the document, sheet_B overwrites sheet_A and sheet_A is not there anymore. I've set the append = TRUE
already. not sure what the issue is.
I have always troubles using xlsx
package because of its java dependency. openxlsx
works fine for me creating a list of named dataframes where name is the sheet name and dataframe is the data that we want to write.
A <- data.frame(a=1:10)
B <- data.frame(a=2:11)
list_df <- list(sheet_A = A, sheet_B = B)
openxlsx::write.xlsx(list_df, 'A.xlsx')
I think the workflow is to create or open a workbook, add a worksheet, write the data to the worksheet and then save the workbook.
Examples:
library(openxlsx)
A=data.frame(a=1:10)
B=data.frame(a=2:11)
C=data.frame(a=3:12)
## just to show the individual steps:
wb <- createWorkbook()
addWorksheet(wb, sheetName="sheet_A")
writeData(wb, sheet = "sheet_A", A)
addWorksheet(wb, sheetName="sheet_B")
writeData(wb, sheet = "sheet_B", B)
saveWorkbook(wb, file="A.xlsx", overwrite = TRUE)
## short version of the above:
write.xlsx(list(sheet_A = A, sheet_B = B), 'A.xlsx')
## add to existing file:
wb <- loadWorkbook("A.xlsx")
addWorksheet(wb, sheetName="sheet_C")
writeData(wb, sheet = "sheet_C", C)
saveWorkbook(wb, file="A.xlsx", overwrite = TRUE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.