Mohit
Mohit

Reputation: 489

Formatting using addstyle in openxlsx package

Question 1

In the code below, while performing the run, all the outputs is displayed in RStudio console.

This particularly happens if the code add style is in the loop for different workbook tabs. I have used sapply.

i would want this to run silently without displaying anything in console.

Question 2

Is it possible to not display the worksheet name in the console when creating the workbook tabs using loop/sapply.

library(openxlsx)
set.seed(2)
dat = data.frame(v1=LETTERS[1:10], v2=runif(10), v3=letters[1:10], v4=runif(10))
wb = createWorkbook()
sapply(paste0("Data",1:10),function(x){addWorksheet(wb,x)})
pct = createStyle(numFmt="0%")
sapply(paste0("Data",1:10),function(x){writeData(wb, x, dat)})
sapply(paste0("Data",1:10),function(x){addStyle(wb, x, style=pct, cols=c(2,4), rows=2:(nrow(dat)+1), gridExpand=TRUE)})
saveWorkbook(wb, "my_workbook.xlsx")

Upvotes: 0

Views: 144

Answers (1)

Edward
Edward

Reputation: 18708

One way is to assign the unwanted output to an R object:

wb = createWorkbook()
x <- sapply(paste0("Data",1:10),function(x){addWorksheet(wb,x)})

x <- sapply(...)
x <- sapply(...)

And you can combine those 3 sapply calls in to one:

foo1 <- function(data) {
  wb = createWorkbook()
  
  x <- sapply(paste0("Data",1:3), function(x) { 
    addWorksheet(wb, x) 
    pct = createStyle(numFmt="0%")
    writeData(wb, x, data)
    addStyle(wb, x, style=pct, cols=c(2,4), rows=2:(nrow(data)+1), gridExpand=TRUE)
  })
  
  saveWorkbook(wb, "my_workbook.xlsx", overwrite = FALSE)
}

Upvotes: -1

Related Questions