2

I'm creating a pretty basic report adding small tables to a docx in a loop. I'd like to fit them to the width of the page or at least align the table (not cells' content) to the left. It should be quite an easy task but I found only references related to:

  • alignment of cell content (package manual)
  • docs built in Rmarkdown (1,2)

I tried the solutions suggested in the references but they did not work. Here what I'm using (commented rows to show other attempts):

  tbl.params = flextable(fdata) %>%
    delete_part(part = "header") %>%
    #autofit() %>%
    border_remove() %>%
    border_inner_h(part="body", border = small_border ) %>%
    hline_top( border = big_border, part="body") %>%
    bold(j=1) %>%
    set_table_properties(layout = "autofit")
    #fit_to_width(7.5)

Am I making a mistake or missing something? I'm looking for solutions in "pure" Officer (if available).

Nico
  • 191
  • 1
  • 6
  • if in an R Markdown, you can use chunk option `ft.align="left"`. See https://davidgohel.github.io/flextable/reference/knit_print.flextable.html#chunk-options – David Gohel Feb 12 '21 at 17:52
  • sorry, I haven't been clear : I'm looking for a solution not using Rmarkdown but "pure" Officer (if available). I can't get why there's a way in Rmarkdown and not in Officer too. – Nico Feb 15 '21 at 10:35
  • the function to user is `body_add_flextable`. It has an argument align that can be set to `left` – David Gohel Feb 15 '21 at 12:38
  • great, thanks! I added `width(width = 3.5)` to fit the page, even if I was hoping for something more dynamic indipendent from the number of columns. If you answer I'll vote your solution. – Nico Feb 16 '21 at 10:08
  • Yes, `width` control columns widths. You can read the documentation here: https://ardata-fr.github.io/flextable-book/ There are lot of examples. – David Gohel Feb 16 '21 at 15:36

1 Answers1

2

The following script add a flextable in a docx document. The column withs are adjusted by Word and the table is left aligned:

library(officer)
library(flextable)

ftab <- flextable( head( mtcars ) )
ftab <- set_table_properties(ftab, layout = "autofit")
doc <- read_docx()
doc <- body_add_flextable(doc, value = ftab, align = "left")
print(doc, target = "fileout.docx")

enter image description here

David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • 1
    Is there something that would do the same but in an Power Point presentation built with `Officer`? `ph_with()` seems to place the table always at the slide's top left or placeholder's top left. – elmaroto10 Apr 23 '21 at 00:57
  • I assume you did not specify location. See here https://ardata-fr.github.io/officeverse/officer-for-powerpoint.html#content-location – David Gohel Apr 23 '21 at 08:58
  • Thanks, I used `ph_location_template()` to define the offset distance programmatically. – elmaroto10 Apr 26 '21 at 10:30