无法使用 openxlsx2 写入工作表

问题描述 投票:0回答:1

这是我的代表

library(openxlsx2)

wb <- openxlsx2::wb_workbook()
openxlsx2::wb_add_worksheet(wb, "All Courses")

allLines = c("This is the first test", 
             "This is the second test",
             "This is the third test")
openxlsx2::wb_add_data(wb, sheet = "All Courses", allLines, start_col = 1, start_row = 1)
openxlsx2::wb_save(wb, file = "C:/Temp/My xlsx2 Test.xlsx", overwrite = TRUE)

当我运行此代码时,我可靠地收到以下错误消息:

openxlsx2::wb_add_data(wb, sheet = "All Courses", allLines, start_col = 1, start_row = 1)
Error in wb$.__enclos_env__$private$get_sheet_index(sheet) : 
  Sheet name(s) not found: all courses

我不知道这是一个错误还是我做错了什么。预先感谢您的帮助

托马斯·飞利浦

r xlsx openxlsx
1个回答
0
投票

问题是,使用

wb_xxx
系列函数,您必须将结果分配回
wb
对象,即使用
wb <- openxlsx2::wb_xxx(...)
:

library(openxlsx2)

allLines <- c(
  "This is the first test",
  "This is the second test",
  "This is the third test"
)

wb <- openxlsx2::wb_workbook()
wb <- openxlsx2::wb_add_worksheet(wb, "All Courses")
wb <- openxlsx2::wb_add_data(wb,
  sheet = "All Courses", allLines,
  start_col = 1, start_row = 1
)
openxlsx2::wb_save(wb, file = "test.xlsx", overwrite = TRUE)

我想避免您可以使用

wb$xxx
调用工作簿方法,如下所示:

wb <- openxlsx2::wb_workbook()
wb$add_worksheet("All Courses")
wb$add_data(
  sheet = "All Courses", allLines,
  start_col = 1, start_row = 1
)
wb$save(file = "test1.xlsx", overwrite = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.