如何解决使用 openxlsx 在 R 中使用 write.xlsx 创建的 Excel 文件的密码保护
我想用密码保护我使用特定工作流程创建的大量 .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,password = "random-password") :
# First argument must be a Workbook.
由 reprex package (v2.0.0) 于 2021 年 7 月 14 日创建
解决方法
您需要先创建一个工作簿对象,因为我认为这就是错误所指示的内容。 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,protect = TRUE,password = "Password") #Protect each sheet
})
saveWorkbook(wb,"example.xlsx",overwrite = TRUE)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。