R XLConnect styling does not persist - r

I'm facing an issue while trying to format/style an existing excel file with data.
I want to change the format of a numeric cell, add background color and a border.
require(XLConnect)
wb <- loadWorkbook("example.xlsx", create = FALSE)
cs <- createCellStyle(wb)
setDataFormat(cs, format = "###,##0")
setFillBackgroundColor(cs, color = XLC$"COLOR.YELLOW")
setBorder(cs, side = "all", type = XLC$"BORDER.THIN",
color = XLC$"COLOR.BLACK")
setCellStyle(wb, sheet = "PSNB", row = 24, col = 3, cellstyle = cs)
saveWorkbook(wb)
After running the above code, the cell doesn't have the background color (Yellow) and the data format persisted.
When i double click on the cell, i can see the background color changing to yellow and the commas(Ex: 100,000) appearing.
Any help would be greatly appreciated!
I'm using XLConnect 0.2-13

I think you are rather looking to set the fill foreground color instead of the fill background color. Background colors are usually only needed in conjunction with non-solid fill patterns (see setFillPattern).
The following may do what you are looking for:
require(XLConnect)
wb <- loadWorkbook("example.xlsx", create = FALSE)
cs <- createCellStyle(wb)
setDataFormat(cs, format = "###,##0")
setFillForegroundColor(cs, color = XLC$"COLOR.YELLOW")
setFillPattern(cs, fill = XLC$FILL.SOLID_FOREGROUND)
setBorder(cs, side = "all", type = XLC$"BORDER.THIN",
color = XLC$"COLOR.BLACK")
setCellStyle(wb, sheet = "PSNB", row = 24,col = 3, cellstyle = cs)
saveWorkbook(wb)
Note the use of setFillForegroundColor and setFillPattern instead of setFillBackgroundColor.

Related

Choosing individual colors for a cell in a table using kable

Is it possible to choose your own color for a cell when creating a table using kable.
In the folowing code from the kable documentation, it shows how you can choose a spectrum (from a couple of options) of colors for a row or column, but I want 1 color for 1 cell. That I can export to a PDF, using knitr.
vs_dt <- iris[1:10, ]
vs_dt[5] <- cell_spec(vs_dt[[5]], color = "white", bold = T,
background = spec_color(1:10, end = 0.9, option = "D", direction = -1))
15
kbl(vs_dt, booktabs = T, escape = F, align = "c")
Thank you
If you would only need 1 color for 1 cell, you can specify the row and column of that cell to be modified.
vs_dt <- iris[1:10, ]
#needed as they are factors
vs_dt$Species <- as.character(vs_dt$Species)
#only the first entry of the Species column
vs_dt[1,5] <- cell_spec(vs_dt[1,5], color = "white", bold = T,
background = "red")
# you can also change some of them excluding the cell.
vs_dt[2:10,5] <- cell_spec(vs_dt[2:10,5], bold = T)
kbl(vs_dt, booktabs = T, escape = F, align = "c")

addStyle function in openxlsx does not fill cells in excel spreadsheet with the right color

Consider the following code block from the r package openxlsx.
I'm trying to fill certain cells in the excel spreadsheet with a particular color.
This is the code I used in order to do this.
library(openxlsx)
# Create a new workbook
wb <- createWorkbook("My name here")
# Add a worksheets
addWorksheet(wb, "Expenditure", gridLines = FALSE)
addWorksheet(wb, "Income", gridLines = FALSE)
# write data to worksheet 1
writeData(wb, sheet = 1, USPersonalExpenditure, rowNames = TRUE)
# Create style object in order to fill certain cells in the excel spreadsheet.
Styling_object <- createStyle(fontColour = "red", bgFill = "yellow")
# Add style to cell in row 2 column 1.
addStyle(wb, sheet = 1, style = Styling_object, rows = 2, cols = 3)
# Add style to cell in row 4 column 3.
addStyle(wb, sheet = 1, style = Styling_object, rows = 4, cols = 3)
# save the workbook
saveWorkbook(wb, "testing_add_style_1.xlsx", overwrite = TRUE)
What I don't understand is why the cells that I specified to be filled up in the excel sheet is filled up with the wrong color. I specified the bgfill argument in the createStyle to be "yellow" which is the fill color I want for the specified cells, but for some reason the cell is filled with a black color in the resulting excel spreadsheet.
This is what I get in my excel spreadsheet.
While it should look something like this:
Use fgFill instead of bgFill. bgFill is for conditional formatting.
Styling_object <- createStyle(fontColour = "red", fgFill = "yellow")

How do I format an entire row within xlsx based on a cell character in R

I am using R to edit an xlsx worksheet. I would like to format the worksheet with colored rows based on character values in a specific column, then save the workbook in xlsx form. I successfully loaded the workbook using xlsx in R. I can run through the characters in the workbook and change that specific cell background color based on a condition, but am having trouble changing the color of that entire row.
My question is, how can I make the entire row a solid color, rather than just the cell? So far, I have followed the instructions and code located here:
Color cells with specific character values in r to export to xlsx
What would you have to add to the code in the above link to make the entire row the same color as the specific cell that was targeted?
greenStyle <- createStyle(fontColour = "#000000", bgFill = "green")
yellowStyle <- createStyle(fontColour = "#000000", bgFill = "yellow")
conditionalFormatting(wb, "entire report", cols=1:12, rows=1:2000, rule="Finished", style = greenStyle, type = "contains")
conditionalFormatting(wb, "entire report", cols=1:12, rows=1:2000, rule="In Process", style = yellowStyle, type = "contains")
saveWorkbook(wb, file, overwrite=TRUE)
This question is from some time ago, I was looking to do this, then found the answer and wanted to share (I am the author of the post referred in the question btw :) )
So, in order to color an entire row, I made a reproducible example:
Reproducible example:
dfX <- data.frame('a' = c(1:4),
'b' = c(1:2,2:1),
'c' = LETTERS[1:4],
'e' = LETTERS[1:2][2:1],
'f' = c('Finished', 'In Process', 'In Process', 'In Process'))
library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "Sheet", gridLines = TRUE)
writeData(wb, "Sheet", dfX)
greenRows = data.frame(which(dfX == "Finished", arr.ind=TRUE))
yellowRows = data.frame(which(dfX == "In Process", arr.ind=TRUE))
## Here I create data frames where it states which rows and columns
## have 'Finished' and which have 'In Process'. From here I want to keep only the
## rows from these data frames.
# Create a heading style
Heading <- createStyle(textDecoration = "bold", border = "Bottom")
# Row styles
greenStyle <- createStyle(fontColour = "#000000", fgFill = "green")
yellowStyle <- createStyle(fontColour = "#000000", fgFill = "yellow")
Important Note: I use "fgFill" instead of "bgFill" because in order to do this, we will use addStyle (and not conditionalFormatting), and in the documentation, it states that bgFill is only for conditionalFormatting
# Apply header style:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = 1, style = Heading)
# Apply greenStyle:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = greenRows[,1]+1,
style = greenStyle, gridExpand = TRUE)
# Apply yellowStyle:
addStyle(wb, "Sheet", cols = 1:ncol(dfX), rows = yellowRows[,1]+1,
style = yellowStyle, gridExpand = TRUE)
saveWorkbook(wb, file, overwrite=TRUE)
Note that in "rows = " I input greenRows[,1]+1, which means only the first column of the greenRows data.frame, plus 1 (the first row would be the header, so skip this one)
Also note that in the last line, in the file part you should specify the directory where to save the file with the .xlsx termination, such as:
saveWorkbook(wb, file = "C:/Documents/newfile.xlsx", overwrite=TRUE)
This post, though not the same question, helped me.

Watermark adding in R

I am using magick library in R. I want to add watermark on some pictures.
I used image_annotatefunction as below.
img <- image_read("C:\\Users\\Maydin\\Desktop\\manzara.png")
image_annotate(img, "my watermark", gravity = "northwest", location = "+200+275",
degrees = -30, size =50, font = NULL, color = "transparent",
strokecolor = "gray90", boxcolor = NULL)
At the end, the output looks like this;
However, what I want to have is something like this ,
Is that doable in magick in R?
For instance, this
download.file("https://i.stack.imgur.com/7X5To.png", tf<-tempfile(fileext = ".png"), mode="wb")
library(magick)
img <- image_read(tf)
library(extrafont)
truetype_path <- paste0("#", subset(fonttable(), FullName=="Matura MT Script Capitals", fontfile)[1,])
image_annotate(img, "my watermark", gravity = "northwest", location = "+70+220",
degrees = -30, size = 80, font = truetype_path, color = "#FFFFFF66",
strokecolor = NULL, boxcolor = NULL)
gives this image:
I.e., choose a nice font like maybe Matura MT Script Capitals, tell image_annotate where to find it on your harddrive, adjust the opacity in the color argument - et voila. The font does not drop a shadow or show a relief, but maybe you can emulate this by plotting the text two times, the dark shadow one with a little offset to the other light one.
#lukA nicely demonstrates a solution using extrafonts package with magick package, but it looks like you can refer to the font by name within image_annotate() without the clever lookup of the full path. Use extrafonts::fonttable() to find the name.
library(extrafonts)
library(magick)
#download original example file
download.file("https://i.stack.imgur.com/7X5To.png", tf<-tempfile(fileext = ".png"), mode="wb")
img <- image_read(tf)
#Use stroke to create an outline of the text with 50% alpha
magick::image_annotate(img, "Preview", location = "+100+175", degrees = -30, size=75, weight=700, font = "MonotypeCorsiva" , color = "transparent",
strokecolor = "#00000050", boxcolor = NULL)

Indent a Flextable made with R-ReporteRs

I want to indent a (flex)table created with the ReporterRs package. Here's an example:
library(ReporteRs)
df <- data.frame(Column1 = 1:5, Column2 = c("a","b","c","d","e"))
Mydoc = docx(title="A testdoc for testing tables")
options('ReporteRs-fontsize'=10, 'ReporteRs-default-font'='Arial')
FTab = FlexTable( data = df, add.rownames = FALSE, header.columns = TRUE,
body.text.props = textProperties( font.size = 10,font.family = "Arial" ),
header.text.props = textProperties( font.size = 10,font.family = "Arial", font.weight = "bold"))
FTab = setFlexTableBorders(FTab,inner.vertical = borderNone(),inner.horizontal = borderNone(),
outer.vertical = borderNone(),
outer.horizontal = borderProperties(color = "black", style = "solid", width = 1))
Mydoc = addFlexTable(Mydoc, FTab)
nu <- format(Sys.time(), "%Y%m%d%H%M")
writeDoc(Mydoc, paste0("testreport_",nu,".docx"))
This creates a docx with a left aligned table. I want the table to move 1.5 cm to the right. So no center or right alignment, but an indentation of 1.5 cm. Is this possible? For text, I can use a pre-defined style that indents 1.5 cm, but for tables that doesn't seem possible. Or is it?
As a workaround, I could add an extra column at the left, without any borders or text. But I prefer a neat solution.
From the package documentation, unless you want to write a patch, it seems you'd better go with the invisible column:
Function addFlexTable
add FlexTable to document objects.
Word and html document
Add a FlexTable object in a document object with the function addFlexTable.
Expected arguments are:
the document object
the FlexTable object
eventually a parProperties object to define alignement. Note that with docx objects, only alignment will be used, if you’d like to add space around a table, specify padding on preceding and or following paragraph.

Resources