R -openxlsx - 删除多个工作表

R -openxlsx - delete multiple worksheets

有没有办法从 openxlsx 的工作簿中删除多个工作表? 或者只保留选定的工作表?

您可以使用 openxlsx 包中的 removeWorksheet

本例摘自reference manual的第69页。

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

编辑:

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

reprex package (v2.0.1)

于 2021-11-25 创建