简体   繁体   English

在 R 中使用 write.xlsx package 时出错

[英]Error in using the write.xlsx package in R

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.错误是当我打开文档时, sheet_B 覆盖 sheet_A 并且 sheet_A 不再存在。 I've set the append = TRUE already.我已经设置了append = TRUE not sure what the issue is.不知道是什么问题。

I have always troubles using xlsx package because of its java dependency.由于它的 java 依赖性,我一直在使用xlsx package 时遇到麻烦。 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. openxlsx对我来说很好,可以创建一个命名数据框列表,其中 name 是工作表名称,dataframe 是我们要写入的数据。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM