How do I autofit the column width using openxlsx
?
One of my columns has a date variable (eg. 21-08-2017
) and if copied using ctrl+c
I had the same issues as above, but was working with a list of data frames. Using the tidyverse, I modified Rick's answer to account for that. I also didn't want column widths wider than 75. This still didn't fix the date issue described above. I didn't want the timestamp to show with my dates and I found you can set the options for how dates are formatted in Excel. So for that I used options("openxlsx.datetimeFormat" = "mm/dd/yyyy"). More info on formatting here
myList <- list(A = data.frame(ID = c("AAA", "AAA"),
Test = c(1, 1),
Value = 1:2),
B = data.frame(ID = c("BBB", "BBB", "BBB"),
Test = c(1, 3, 5),
Value = 1:3),
C = data.frame(Test = c(1, 3, 5),
Value = 1:3))
data_cols <- myList %>%
map(~ 1:ncol(.), .depth = 2)
width_vec <- myList %>%
map(~ summarise_all(., funs(max(nchar(as.character(.)))), na.rm = TRUE), .depth = 2) %>%
map(~ unlist(., use.names = FALSE), .depth = 2) %>%
map(~ . + 2, .depth = 2)
width_vec_header <- map(myList, ~ nchar(names(.)) + 2, .depth = 2)
max_vec <- map2(width_vec, width_vec_header, ~ pmin(75, pmax(.x, .y, 0)), .depth = 2)
pwalk(list(names(myList), data_cols, max_vec), ~ setColWidths(wb, ..1, ..2, widths = ..3))