简体   繁体   中英

Exporting several tables to word documents using r package 'flextable'

I am trying to export two (flex)tables within the same word document. Here what I have:

df1 <- data.frame(a = 1:3, b = 1:3)
df2 <- data.frame(c = 11:13, d = 11:13)

library(flextable)
df1_ft <- regulartable(df1)
df2_ft <- regulartable(df2)

library(officer)
word_export <- read_docx()
word_export <- body_add_flextable(word_export, df1_ft)
word_export <- body_add_flextable(word_export, df2_ft)
print(word_export, 'try.docx')

Yet, the results is a single table containing both tables. Any idea how I can add to two tables one after the other?

The two tables are being output to Word one after the other, and as there are no line breaks between them they appear as one. Simplest solution is to place a paragraph with empty text between them:

word_export <- read_docx()
body_add_flextable(word_export, df1_ft)
body_add_par(word_export, value = "")
body_add_flextable(word_export, df2_ft)
print(word_export, 'try.docx')

在此输入图像描述

You can also see that you don't need to repeatedly assign the output of each body_add_* line back to your word_export file - the Word file is updated directly by each call.

You can try

library(flextable)
library(tidyverse)
library(officer)
# write function
write_word_table <- function(var, doc){
  doc %>%
    body_add_flextable(var) %>% 
    body_add_break() }

# list of tables and the doc
my_list <- list(df1_ft <- regulartable(df1),
              df2_ft <- regulartable(df2))
my_doc <- read_docx()

# use walk (the invisible function of map) to include all tables in one doc
walk(my_list, write_word_table, my_doc) 
print(my_doc, target = "c:/Users/tremmel/Desktop/Doc1.docx") %>% invisible()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM