Home > OS >  R -openxlsx - delete multiple worksheets
R -openxlsx - delete multiple worksheets

Time:11-26

Is there a way to remove multiple worksheets from a workbook in openxlsx? Or to keep only selected worksheets?

CodePudding user response:

You can use removeWorksheet from openxlsx package.

This example is taken out from page 69 of the reference manual.

wb <- createWorkbook()
addWorksheet(wb, sheetName = "Sheet 1")
addWorksheet(wb, sheetName = "Sheet 2")
writeDataTable(wb, sheet = "Sheet 1", x = iris, tableName = "iris")
writeDataTable(wb, sheet = 1, x = mtcars, tableName = "mtcars", startCol = 10)
removeWorksheet(wb, sheet = 1) ## delete worksheet removes table objects

edit:

library(openxlsx)
library(purrr)

nms <- c("Sheet 1","Sheet 2","Sheet 3")

wb <- createWorkbook()

nms %>% 
 walk(~ addWorksheet(wb, sheetName = .))

addWorksheet(wb, sheetName = 'sheet 4')

wb
#> A Workbook object.
#>  
#> Worksheets:
#>  Sheet 1: "Sheet 1"
#>  
#> 
#>  Sheet 2: "Sheet 2"
#>  
#> 
#>  Sheet 3: "Sheet 3"
#>  
#> 
#>  Sheet 4: "sheet 4"
#>  
#> 
#>  
#>  Worksheet write order: 1, 2, 3, 4
#>  Active Sheet 1: "Sheet 1" 
#>  Position: 1

nms %>% 
  walk(~ removeWorksheet(wb, .))

wb
#> A Workbook object.
#>  
#> Worksheets:
#>  Sheet 1: "sheet 4"
#>  
#> 
#>  
#>  Worksheet write order: 1
#>  Active Sheet 1: "sheet 4" 
#>  Position: 1

Created on 2021-11-25 by the reprex package (v2.0.1)

  • Related