This is one way: openxlsx
does need a fair bit of work but the great thing is you can generally achieve what you want.
library(openxlsx)
library(tibble)
library(dplyr)
df1 <-
mtcars[1:5,1:5] %>%
# to convert row names into a variable
rownames_to_column(var = "model") %>%
# to enable a percentage format to be applied
mutate(disp = disp/100)
df1 <- janitor::adorn_totals(df1)
wb <- createWorkbook()
addWorksheet(wb, "tables")
setColWidths(wb, 1, cols = 1, widths = 25)
writeData(wb, 1, df1)
header_style <- createStyle(fgFill = "#4F81BD", halign = "center", textDecoration = "bold", fontColour = "white")
addStyle(wb, 1, style = header_style, rows = 1, cols = 1:ncol(df1))
name_style <- createStyle(fgFill = "gray70", halign = "center", fontColour = "white")
addStyle(wb, 1, style = name_style, rows = 2 : nrow(df1), cols = 1)
percent_style <- createStyle(halign = "center", numFmt = "00%")
addStyle(wb, 1, style = percent_style, rows = 2 : nrow(df1), which(colnames(df1) == "disp"))
center_style <- createStyle(halign = "center")
addStyle(wb, 1, style = center_style, rows = 2 : nrow(df1), cols = which(!colnames(df1) %in% c("model", "disp")), gridExpand = TRUE)
total_style <- createStyle(fgFill = "yellow", halign = "center", fontColour = "black", fontSize = 14)
addStyle(wb, 1, style = total_style, rows = nrow(df1) + 1, cols = 1:ncol(df1))
saveWorkbook(wb, "openxlsx_mtcars_eg.xlsx", overwrite = TRUE)
Created on 2022-01-31 by the reprex package (v2.0.1)
