ropenxlsx2

how I can customize font color using conditional format in openxlsx2 in r?


Hi and thanks for reading me Im currently working in an excel file with a conditional format using R and the package openxlsx2, but when I add the style I get an error in the document output. My code is:

library(openxlsx2)

wb_workbook(creator = "Jorge Hernandez", title = "accounts MX summarise", category = "sales") |>
  wb_add_worksheet("Evolucion", gridLines = F, tabColor = "#4e6fa3") |>
  wb_add_data(
    x = iris
  ) |> 
  wb_add_conditional_formatting(type = "expression",
                                cols = 1:ncol(iris),
                                rows = 2:200,
                                style = create_dxfs_style(font_color = wb_color(hex = "FF9C6500"),
                                                          bgFill = wb_color(hex = "FFFFEB9C")),
                                rule = ">0" ) |> 
  wb_save(
    path = "/Users/jorgehca/Desktop/data.xlsx"
  )

does anyone knows how I can apply the font color and background color for cell style correctly?


Solution

  • You have to assign the dxf style first:

    library(openxlsx2)
    
    wb_workbook(
      creator = "Jorge Hernandez",
      title = "accounts MX summarise",
      category = "sales"
    ) |>
      wb_add_worksheet(
        "Evolucion",
        grid_lines = FALSE,
        tab_color = "#4e6fa3"
      )|>
      wb_add_data(
        x = iris
      ) |> 
      wb_add_dxfs_style(
        name = "Jorges_CF_style",
        font_color = wb_color(hex = "FF9C6500"),
        bg_fill = wb_color(hex = "FFFFEB9C")
      ) |>
      wb_add_conditional_formatting(
        type = "expression",
        cols = seq_along(iris),
        rows = 2:200,
        style = "Jorges_CF_style",
        rule = ">0" 
      ) |>
      wb_save(temp_xlsx())
    

    It's like this, because it allows you to reuse conditional formatting styles and allows you to use dxf styles that have been loaded.