Skip to content

Instantly share code, notes, and snippets.

@simonthompson99
Last active January 15, 2021 12:45
Show Gist options
  • Save simonthompson99/b2ab910885f73c4d9c0df49068248e1a to your computer and use it in GitHub Desktop.
Save simonthompson99/b2ab910885f73c4d9c0df49068248e1a to your computer and use it in GitHub Desktop.
[Write dataframe to Excel file] Write a simple xlsx spreadsheet of data #r #excel
#-- wrapper function to create a worksheet with particular formatting
writeXlsx <- function(d, fn, sheet_name = ''){
require(openxlsx)
# creates xlsx workbook containing data
# header styling
hs1 <- createStyle(fgFill = "#4F81BD", halign = "LEFT", textDecoration = "Bold", border = "Bottom", fontColour = "white")
cs1 <- createStyle(wrapText = TRUE, halign = 'LEFT', valign = 'top')
wb <- createWorkbook()
addWorksheet(wb, sheetName=sheet_name)
setColWidths(wb, 1, 1:ncol(d), 'auto')
freezePane(wb, 1, firstRow = TRUE)
writeData(wb, 1, d, headerStyle = hs1)
addStyle(wb, 1, style = cs1, rows = 2:(nrow(d) + 1), cols = 1:ncol(d), gridExpand = TRUE)
saveWorkbook(wb, fn, overwrite = TRUE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment