使用openxlsx2写入工作表报错:找不到指定工作表名称
问题描述
我运行以下R代码时持续报错:
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
不确定是软件bug还是操作失误,求帮助。
问题原因与修正
这是操作失误导致的——openxlsx2包采用函数式设计,不会原地修改工作簿对象,调用wb_add_worksheet后需要将返回的新工作簿重新赋值给变量wb,否则原wb依然是空工作簿,自然找不到指定的工作表。
修正后的代码:
library(openxlsx2) # 创建空工作簿 wb <- openxlsx2::wb_workbook() # 添加工作表并重新赋值给wb,保留更新后的工作簿对象 wb <- openxlsx2::wb_add_worksheet(wb, "All Courses") allLines = c("This is the first test", "This is the second test", "This is the third test") # 写入数据后同样重新赋值 wb <- 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)
核心注意点:
- 调用
wb_add_worksheet、wb_add_data这类修改工作簿的函数后,必须将结果重新赋值给wb,确保后续操作基于更新后的工作簿。 - 错误信息中显示小写的
all courses是包内部名称匹配逻辑的细节,本质问题是工作表未被正确添加到工作簿中。
内容的提问来源于stack exchange,提问作者Thomas Philips
相关产品推荐
相关产品推荐

