I loaded an Excel workbook in R and want to do some formatting of the borders in a rectangular range of cells.
- I would like to put a thin border between all cells
- put a thick border around the outside of the range of the cells.
At the moment, I can only see the following approach (as started in the code below):
- Add thin borders in the range
- overwrite the left cells with left thick border and other thin borders
- overwrite the right cells with right thick border and other thin borders
- overwrite each corner cell separately with the correct borders
Is there an easier way of achieving this?
Edit 1:
If I use stack = TRUE
in the second call I can skip the corners:
library(openxlsx)
wb <- openxlsx::createWorkbook()
openxlsx::addWorksheet(
wb = wb,
sheetName = "Borders"
)
rangeRows = 2:5
rangeCols = 4:8
insideBorders <- openxlsx::createStyle(
border = c("top", "bottom", "left", "right"),
borderStyle = "thin"
)
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = insideBorders,
rows = rangeRows,
cols = rangeCols,
gridExpand = TRUE
)
openxlsx::openXL(wb)
## left borders
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = openxlsx::createStyle(
border = c("left"),
borderStyle = c("thick")
),
rows = rangeRows,
cols = rangeCols[1],
stack = TRUE,
gridExpand = TRUE
)
##right borders
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = openxlsx::createStyle(
border = c("right"),
borderStyle = c("thick")
),
rows = rangeRows,
cols = tail(rangeCols, 1),
stack = TRUE,
gridExpand = TRUE
)
## top borders
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = openxlsx::createStyle(
border = c("top"),
borderStyle = c("thick")
),
rows = rangeRows[1],
cols = rangeCols,
stack = TRUE,
gridExpand = TRUE
)
##bottom borders
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = openxlsx::createStyle(
border = c("bottom"),
borderStyle = c("thick")
),
rows = tail(rangeRows, 1),
cols = rangeCols,
stack = TRUE,
gridExpand = TRUE
)
openxlsx::openXL(wb)
Original Code:
library(openxlsx)
wb <- openxlsx::createWorkbook()
openxlsx::addWorksheet(
wb = wb,
sheetName = "Borders"
)
rangeRows = 2:5
rangeCols = 4:8
insideBorders <- openxlsx::createStyle(
border = c("top", "bottom", "left", "right"),
borderStyle = "thin"
)
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = insideBorders,
rows = rangeRows,
cols = rangeCols,
gridExpand = TRUE
)
openxlsx::openXL(wb)
leftBorders <- openxlsx::createStyle(
border = c("top", "bottom", "left", "right"),
borderStyle = c("thin", "thin", "thick", "thin")
)
openxlsx::addStyle(
wb = wb,
sheet = "Borders",
style = leftBorders,
rows = rangeRows,
cols = rangeCols[1],
gridExpand = TRUE
)
openxlsx::openXL(wb)