简体   繁体   中英

Password protecting an Excel file created using write.xlsx in R with openxlsx

I want to password protect a large number of .xslx files I'm creating using a particular workflow. The workflow is simple and relies on having a named list of smaller data frames that I write using the write.xlsx command from openxlsx in R. Is there a solution to password protecting these files with protectWorkbook using a similar workflow? Thank you.

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.

Created on 2021-07-14 by the reprex package (v2.0.0)

You need to create a workbook object first as I think that is what the error is indicating. The write.xlsx isn't recognized as a workbook object and that is required for the protectWorkbook argument.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM