Created
October 15, 2017 16:12
-
-
Save kaz-yos/c0f42348e525cd78b2b371e55fb9d008 to your computer and use it in GitHub Desktop.
Write multiple data_frames to a single xlsx file (use openxlsx)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Write multiple data_frames to a single xlsx file (use openxlsx) | |
write_lst_of_df_to_xlsx <- function(lst_df, file, font_size) { | |
## Create a workbook object with one sheet | |
## https://rdrr.io/cran/openxlsx/man/setColWidths.html | |
wb <- createWorkbook() | |
## Work on each data_frame | |
for (i in seq_along(lst_df)) { | |
sheet_name <- ifelse(is.null(names(lst_df[i])), | |
## Index if not available | |
i, | |
## Otherwise name | |
names(lst_df[i])) | |
## Add a worksheet with the name | |
addWorksheet(wb, sheetName = sheet_name) | |
## Write data frame data to the workbook object | |
writeData(wb, sheet = sheet_name, x = lst_df[[i]]) | |
## Format the variable name column | |
## https://rdrr.io/cran/openxlsx/man/createStyle.html | |
varname_style <- createStyle(fontSize = font_size, halign = "left", valign = "center") | |
addStyle(wb, sheet = sheet_name, style = varname_style, | |
rows = seq_len(nrow(lst_df[[i]]) + 1), | |
cols = 1, | |
gridExpand = TRUE) | |
## Format all other columns | |
varval_style <- createStyle(fontSize = font_size, halign = "center", valign = "center") | |
addStyle(wb, sheet = sheet_name, style = varval_style, | |
rows = seq_len(nrow(lst_df[[i]]) + 1), | |
cols = seq_len(ncol(lst_df[[i]]))[-1], | |
gridExpand = TRUE) | |
## Fix column width automatically | |
setColWidths(wb, sheet = sheet_name, cols = seq_len(ncol(lst_df[[i]])), widths = "auto") | |
} | |
## Save to a file | |
saveWorkbook(wb, file = file, overwrite = TRUE) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment