Create border for an XLSX through R

Viewed 451

How do I create a border around a block in a sheet with 24 rows starting from the 3rd row and 10 columns starting from 2nd column in R for an XLSX workbook

I tried using Border and CellBlock but no luck

1 Answers

Using openxlsx you can try the following (reproducible example).

Create individual styles for left, right, top, and bottom borders, and use addStyle for appropriate rows/columns (e.g., row 3, columns 2-12 should all have a top border).

Make sure when adding styles you don't overwrite and cut off the corners; use stack = TRUE to prevent this from happening.

library(openxlsx)

# Create workbook
wb <- createWorkbook()

# Add sheet
addWorksheet(wb, sheetName = "cars")
  
# Write dataframe
writeData(wb, sheet = "cars", x = mtcars[1:24,], startRow = 3, startCol = 2)
  
# Apply styles
addStyle(wb, sheet = "cars", style = createStyle(border = "Top"), rows = 3, cols = 2:12)
addStyle(wb, sheet = "cars", style = createStyle(border = "Bottom"), rows = 27, cols = 2:12)
addStyle(wb, sheet = "cars", style = createStyle(border = "Left"), rows = 3:27, cols = 2, stack = TRUE)
addStyle(wb, sheet = "cars", style = createStyle(border = "Right"), rows = 3:27, cols = 12, stack = TRUE)

# Save workbook
saveWorkbook(wb, "border_test.xlsx", overwrite = TRUE)
Related