Search code examples
rflextable

FlexTable output .docx horizontal table adjusted to narrow margins


I have a flextable object called html_table which I want to directly put in a word document, in horizontal layout with narrow margins. I face 2 problems:

1) The approach suggested in the vignette produces extra pages (one before, one after the table). I think this is a known issue but not clear how to solve it.
2) I would like to have narrow margins and the resulting table on horizontal pages to be automatically fitted to the page. I want this so that I can print the table using as much page as I can. My current approach is to manually open the document, change the layout and select "autofit" on Word.

Here's the code I'm using to produce the document. For illustrative purposes, I will use mtcars for my table, but the real one has more rows than mtcars.

html_table <- regulartable(mtcars)    
doc <- read_docx() %>%
      # Make it landscape
      body_end_section_continuous() %>%
      # Add the table
      body_add_flextable(value = html_table,
                         split = TRUE
                        ) %>%
      body_end_section_landscape()
    # Write the .docx
    print( doc, target = "my_table.docx" )

Solution

  • In Word document, sections are only defined when they stop (I can not explain why it has been made that way but this is how the underlying xml is...). Also a landscape oriented section need a page break if the preceding section is not landscape oriented.

    To autofit a flextable, use function autofit.

    library(flextable)
    library(officer)
    library(magrittr)
    
    html_table <- regulartable(mtcars) %>% 
      autofit()
    
    doc <- read_docx() %>%
      body_add_flextable(value = html_table, split = TRUE) %>%
      body_end_section_landscape() %>% # a landscape section is ending here
      print( target = "my_table.docx" )
    

    enter image description here

    If you don't want extra page, you will need a template with a default page orientation as landscape. Also, you would not need any code to manage orientation nor margins.