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