formatting tables in xlsx files

I am trying to create function for formatting every tables in xlsx file.

I want to save N numbers of Tables in xlsx and formatting all the tables in xlsx file. but its formatting the first table only.

library(openxlsx)
format_tbl <- function(workbook,tbll){
  setColWidths(workbook, 1,cols = 1:ncol(tbll), widths = "auto")
  writeData(workbook, 1, tbll)
  
  header_style <- createStyle(fgFill = "#009DE0", halign = "center", textDecoration = "bold", fontColour = "white")
  addStyle(workbook, 1, style = header_style, rows = 1, cols = 1:ncol(tbll))
  
  name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
  addStyle(workbook, 1, style = name_style, rows = 2 : nrow(tbll), cols = 1)
  
  percent_style <- createStyle(halign = "center", numFmt = "00%")
  addStyle(workbook, 1, style = percent_style, rows = 2 : nrow(tbll), which(colnames(tbll) == "disp"))
  
  center_style <- createStyle(halign = "center")
  addStyle(workbook, 1, style = center_style, rows = 2 : nrow(tbll), cols = which(!colnames(tbll) %in% c("model", "disp")), gridExpand = TRUE)
  
  total_style <- createStyle(fgFill = "#009DE0", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = total_style, rows = nrow(tbll), cols = 1:ncol(tbll))
  
  Na_style <- createStyle(fgFill = "#00968F", halign = "center", fontColour = "black", fontSize = 12)
  addStyle(workbook, 1, style = Na_style, rows = nrow(tbll)+1, cols = 1:ncol(tbll))
  
}

t1 = mtcars
t2 = mtcars[,1:5]
t3= iris
t4 = iris[1:8,] 

format_tbl(workbook=wb,tbll=t1)
format_tbl(workbook=wb,tbll=t2)
format_tbl(workbook=wb,tbll=t3)
format_tbl(workbook=wb,tbll=t4)

tbls <- list(t1,t2,t3,t4)



startRows <- c(0, cumsum(2 + sapply(tbls, nrow)[-length(tbls)])) + 1

fn <- tempfile(fileext = "xlsx")

wb <- createWorkbook()
addWorksheet(wb, "tbls")
mapply(function(tbl, startRow) writeData(wb, "tbls", x = tbl, startRow = startRow), tbls, startRows)

saveWorkbook(wb, fn, overwrite = TRUE) %>% file.show(.)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.