R - Autofit Excel column width

后端 未结 4 1919
再見小時候
再見小時候 2021-02-02 01:30

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

4条回答
  •  猫巷女王i
    2021-02-02 02:02

    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))
    

提交回复
热议问题