Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Font Coloring Using xlsx Package in R

Tags:

r

xlsx

I am writing an R function to save out pre-formatted data frames. Part of the format template calls for changing the column heading font color. The cell styling returns the correct alignment and bolding, but the text is still black.

The below is a bare version to demonstrate my font coloring problem (just change the file_path variable to a location that exists).

library(xlsx)
file_path <- "C:/Users/.../Desktop/tst.xlsx"
wb <- createWorkbook()

headerStyle <- CellStyle(wb,
                         font = Font(wb, isBold=TRUE, color = "#ffffff"),
                         fill = Fill(foregroundColor = "#2db6e8",
                                     pattern = "SOLID_FOREGROUND"),
                         alignment = Alignment(wrapText = TRUE,
                                               horizontal = "ALIGN_CENTER",
                                               vertical = "VERTICAL_CENTER")
)

x <- mtcars
sheet <- createSheet(wb, "test")

cellBlock <- CellBlock(sheet,
                       startRow = 1,
                       startCol = 1,
                       noRows = nrow(x) + 1,
                       noColumns = ncol(x) + 1,
                       create = TRUE)

CB.setRowData(cellBlock = cellBlock,
              x = colnames(x),
              rowIndex = 1,
              colOffset = 1,
              rowStyle = headerStyle +
                Border(pen = "BORDER_MEDIUM", color = "black",
                       position = "BOTTOM"))

saveWorkbook(wb, file_path)
like image 837
ElizabethAB Avatar asked Dec 30 '25 04:12

ElizabethAB


1 Answers

I was able to get white text using the color index from the INDEXED_COLORS_ constant which is 9 for white. For your example code it would read:

headerStyle <- CellStyle(wb,
          font = Font(wb, isBold=TRUE, color = "9"),
          fill = Fill(foregroundColor = "#2db6e8",
          pattern = "SOLID_FOREGROUND"),
          alignment = Alignment(wrapText = TRUE,
                            horizontal = "ALIGN_CENTER",
                            vertical = "VERTICAL_CENTER")
)
like image 177
JonH Avatar answered Jan 01 '26 17:01

JonH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!