Here is a function that is based on openxlsx
where you specify the workbook (from_wb
) and sheet name/location (from_sheet
) that has the styles and the workbook (to_wb
) and sheet name/location (to_sheet
) to which you want to transfer the style:
Note: I used the purrr
and glue
packages as well, but this could be re-written in base R.
copyStyle <- function(from_wb, to_wb, from_sheet, to_sheet) {
# check for workbook objects
if (!(inherits(from_wb, "Workbook") && inherits(to_wb, "Workbook"))) {
stop("from_wb and to_wb must be Workbook objects.")
}
# get all sheet names from workbooks
from_sheets <- from_wb$sheet_names
to_sheets <- to_wb$sheet_names
# convert sheets from numeric to sheet name. wb$styleObjects uses sheet name
if (is.numeric(from_sheet)) {
from_sheet <- from_wb$getSheetName(from_sheet)
}
if (is.numeric(to_sheet)) {
to_sheet <- to_wb$getSheetName(to_sheet)
}
# if sheet name given check that it exists
if (is.character(from_sheet) && !from_sheet %in% from_sheets) {
stop(glue::glue("{from_sheet} was not found in from_wb"))
}
if (is.character(to_sheet) && !to_sheet %in% to_sheets) {
stop(glue::glue("{to_sheet} was not found in to_wb"))
}
# get from_wb sheet styles
from_styles <- purrr::keep(from_wb$styleObjects, ~ .x$sheet == from_sheet)
# add styles to to_wb
purrr::walk(from_styles, ~ openxlsx::addStyle(to_wb,
to_sheet,
.x$style,
rows = .x$rows,
cols = .x$cols))
return(to_wb)
}
Usage
library(openxlsx)
wb <- loadWorkbook("getStyle.xlsx")
new_wb <- write.xlsx(head(iris), "transfer_style.xlsx")
# can give sheet name or index
copyStyle(from_wb = wb, to_wb = new_wb, from_sheet = "Sheet1", to_sheet = 1)
# must save workbook after copying style
saveWorkbook(new_wb, "transfer_style.xlsx", overwrite = T)
Input
getStyles.xlsx
is a local Excel workbook with multiple styles on several sheets:

Output
transfer_styles.xlsx
:
