setColWidths (..., widths = "auto")usually works to widen columns based on the values present in the workbook. However, I experienced earlier today a failure of this auto-widening feature. I unfortunately cannot provide the confidential data and failed to generate a reproducible example, however, TLDR: The Figure 5 code in the gist below shows how to use the
pmax function to identify the maximum of the header length and body text length, per column.
This is an expounding on my StackOverflow answer here, to which I invite you to respond.
Note: The R code is assembled together as a Gist at the bottom of this post.
Openxlsx will often save an Excel workbook without any width adjustments needed.
Here is the starwars data found in Hadley Wickham’s tidyverse collection of packages.
Looks okay, but columns like E (skin_color) show a truncated header.
We can use widths = “auto” in the setColWidths function to auto-widen the column based on the data. I know of no negatives to doing so and therefore always include this code.
We see that widths = “auto” in the setColWidths function serves us well. All of the column headers can be fully-seen and the same is true for the values in the body. The truncation at the far-right is due to my imperfect screenshotting.
I was hoping to reproduce the problem I experienced earlier by trying the storms dataframe. I am including Figure 3 to further emphasize the power of the openxlsx package (using widths = “auto”) and possibly invite exploration of this “subset of the NOAA Atlantic hurricane database best track data“, which also comes with the tidyverse.
Two-row headers might be valuable for those accustomed to Excel pivot tables. This shows a use of mergecells to create a header for the data frame’s column headers. No problem seen with widths = “auto”.
However, I solved my problem with confidential data with the code associated with figure 5, and it looks a bit better than Figure 4. The height column now has no extraneous space, for example. Depending on your font size and features, you might adjust the width_adjuster object (e.g., increase the number for more space).