Search code examples
rflextableofficer

Multiple flextables in Word using bookmarks and officer


I want to add two flextables at two bookmark locations in 1 Word document. However, when the second one gets added, it puts the second table at the bookmark of the first, and the first table is not in the Word document.

Has anybody else had this problem and knows how to fix it?

Example code:

library(officer)
library(flextable)

variable_1 <- c("text1", "text2", "text3") 
variable_2 <- c(23,45,23) 
variable_3 <- c("column1", "column2", "column3")

df1 = data.frame(variable_1, variable_2) 
df2 = data.frame(variable_3, variable_2)

df1_flex <- flextable(df1) 
df2_flex <- flextable(df2)

doc <- read_docx("X:/My Desktop/test_document.docx") 
doc <- cursor_begin(doc) 
doc <- cursor_forward(doc) 
print(doc, target="X:/My Desktop/test_document_bm.docx")

doc <- read_docx("X:/My Desktop/test_document_bm.docx") 
doc <- body_bookmark(doc, "tabel1") 
doc <- body_replace_flextable_at_bkm(doc, "tabel1", df1_flex) 
doc <- body_bookmark(doc, "tabel2") 
doc <- body_replace_flextable_at_bkm(doc, "tabel2", df2_flex)

docx_bookmarks(doc)

print(doc, target="X:/My Desktop/test_document_result.docx")

This is what the output looks like, instead of the two tables: result


Solution

  • Looks like the bookmarks are being added in the same location, so the latest one overrides earlier additions.

    See if the following works for your:

    library(dplyr)
    
    doc <- read_docx("X:/My Desktop/test_document_bm.docx") %>%
      body_add_par("") %>%
      body_bookmark("table1") %>%
      body_replace_flextable_at_bkm("table1", df1_flex) %>%
      body_add_par("") %>% # 2 line breaks so that the tables are separate from each other
      body_add_par("") %>%
      body_bookmark("table2") %>%
      body_replace_flextable_at_bkm("table2", df2_flex)
    
    print(doc, target="X:/My Desktop/test_document_result.docx")
    

    Screenshot of result:

    result