R - Autofit Excel column width

后端 未结 4 1916
再見小時候
再見小時候 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条回答
  •  时光说笑
    2021-02-02 02:06

    Given that widths = "auto" did not work as you hoped, a more generalized answer to assign the widths based on the lengthiest value + 2 (to handle emboldening):

    width_vec <- apply(DF, 2, function(x) max(nchar(as.character(x)) + 2, na.rm = TRUE)) setColWidths(WB, Sheet, cols = 1:ncol(DF), widths = width_vec)

    And to assign the width based on the column headers:

    width_vec_header <- nchar(colnames(DF)) + 2
    setColWidths(WB, Sheet, cols = 1:ncol(DF), widths = width_vec_header)

    And to assign the width based on the lengthiest string per column, whether the header or the cells in the body, use the "parallel" maximum function (like a vectorized maximum function):
    width_vec <- apply(DF, 2, function(x) max(nchar(as.character(x)) + 2, na.rm = TRUE))
    width_vec_header <- nchar(colnames(DF)) + 2
    max_vec_header <- pmax(width_vec, width_vec_header)
    setColWidths(WB, Sheet, cols = 1:ncol(DF), widths = max_vec_header )

提交回复
热议问题