Captain Tyler
Captain Tyler

Reputation: 594

openxlsx add multiple lines on header/footer

I am trying to build the headers of an excel xlsx workbook with some format. Some strings are too large and need wrapped it.

But when I do it with strwrap adding \n character, setHeaderFooter tell me that I have more than three parameters

for example:

require (openxlsx)
require (tidyverse)

wb0 <- createWorkbook()
addWorksheet(wb0, "Sheet 1")

label <- "&B EJECUTIVOS DE CUENTA: &B"
value <- "FANARA ARIEL GUSTAVO:476, BARETTO ANA SILVINA:34, NO APLICA:32, SANTOS MAXIMILIANO ARIEL:21, AVILA ROBERTO:19, REGGI PABLO:9, Otros:51"


setHeaderFooter (
  wb0, sheet = 1
  , header = c ( 
    # "left side / izquierda"
    strwrap (
      x = paste0 (
          label, " "
        , substr (value, start = 1, stop = 360)
      )
      , width = 45
      , prefix = "\n", initial = ""
    )
    , "center header / centro"
    , "rigth side / derecha"
  ) 
  , footer = c (
    "&[Date]"
    ,  NA
    , "&[File]"
  )
)    

Upvotes: 2

Views: 1859

Answers (1)

eipi10
eipi10

Reputation: 93811

strwrap is creating a vector of length 4, so the total number of elements in your header is 6, rather than the 3 that setHeaderFooter requires.

strwrap(x = paste0 (label, " ", substr (value, start = 1, stop = 360)), 
        width = 45, prefix = "\n", initial = "")

[1] "&B EJECUTIVOS DE CUENTA: &B FANARA ARIEL"    "\nGUSTAVO:476, BARETTO ANA SILVINA:34, NO"   "\nAPLICA:32, SANTOS MAXIMILIANO ARIEL:21,"  
[4] "\nAVILA ROBERTO:19, REGGI PABLO:9, Otros:51"

So let's collapse this into a single string vector by wrapping it in paste:

paste(strwrap(x = paste0 (label, " ", substr (value, start = 1, stop = 360)), 
              width = 45, prefix = "\n", initial = ""), 
      collapse="")

[1] "&B EJECUTIVOS DE CUENTA: &B FANARA ARIEL\nGUSTAVO:476, BARETTO ANA SILVINA:34, NO\nAPLICA:32, SANTOS MAXIMILIANO ARIEL:21,\nAVILA ROBERTO:19, REGGI PABLO:9, Otros:51"

Now you'll get a header with the 3 elements that the function expects. Here's what the header looks like in the Excel file:

enter image description here

Upvotes: 2

Related Questions