我想用密码保护我使用特定工作流程创建的大量 .xslx 文件。工作流程很简单,依赖于我使用 R 中 write.xlsx
中的 openxlsx
命令编写的较小数据帧的命名列表。是否有解决方案可以使用 protectWorkbook
密码保护这些文件使用类似的工作流程?谢谢。
library(tidyverse)
library(openxlsx)
## Create reprex using diamonds
df_ls <- diamonds %>%
select_if(is.ordered) %>%
gather(key, value) %>%
split(.$key)
#> Warning: attributes are not identical across measure variables;
#> they will be dropped
## I like to use lists to write to .xlsx
## because write.xlsx creates each object
## in the list as its own sheet and names
## it using the list names.
.path <- tempfile(fileext = ".xlsx")
write.xlsx(df_ls, file = .path)
## I want to password protect this file(s)
map(.path, ~{protectWorkbook(.x, protect = TRUE, password = "random-password")})
# Error in protectWorkbook(.x, protect = TRUE, password = "random-password") :
# First argument must be a Workbook.
由 reprex package (v2.0.0) 于 2021 年 7 月 14 日创建
答案 0 :(得分:1)
您需要先创建一个工作簿对象,因为我认为这就是错误所指示的内容。 write.xlsx 未被识别为工作簿对象,这是protectWorkbook 参数所必需的。
df_ls <- diamonds %>%
select_if(is.ordered) %>%
gather(key, value) %>%
split(.$key)
wb = createWorkbook()
lapply(seq_along(df_ls), function(i){
addWorksheet(wb=wb, sheetName = names(df_ls[i])) #Add each sheet
writeData(wb, sheet = i, df_ls[[i]]) #Add data to each sheet
protectWorksheet(wb, sheet = i, protect = TRUE, password = "Password") #Protect each sheet
})
saveWorkbook(wb, "example.xlsx", overwrite = TRUE)