使用 openxlsx 在 R 中使用 write.xlsx 创建的 Excel 文件的密码保护

时间:2021-07-14 10:15:08

标签: r excel password-protection openxlsx

我想用密码保护我使用特定工作流程创建的大量 .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 日创建

1 个答案:

答案 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)
相关问题