How to more table with save_as_docx in one single .docx files

161 Views Asked by At

I have created the following list of files:

require(writexl)
write_xlsx(mtcars, 'PQ_ele_com.xlsx')


dir = c('com', 'set', 'rit')
init = c('PQ', 'MG')
inpst = c('_ele_', '_mel_', '_col_')


for (i in dir) {
  for (j in init) {
    for (k in inpst){
      write_xlsx(mtcars[3,],, paste0(j, k, i, '.xlsx')) 
    }
  }
}

setwd("C:/Users/PC/Desktop/my_folder")
files = list.files("C:/Users/PC/Desktop/my_folder", recursive= FALSE, full.names= FALSE)

init = c('PQ', 'MG')
dir = c('com', 'set', 'rit')


files = list.files(recursive= FALSE, full.names= FALSE)
init = c('PQ', 'MG')
dir = c('com', 'set', 'rit')
 
 list3 = NULL
 for (j in init){
   for (k in dir){
     df=c()
     for (i in files){
       if(str_detect(i, pattern = j) & str_detect(i, pattern = k) == TRUE) {
         df=rbind(df,read_excel(i))}
     }
     list3[[j]][[k]] = df
   }
 }

and I would like to save all the tables created with flextable in one single file. I have tried this solution but it can just print the tables on different sheets and reiterated many times. What can I change in them? Would you have some alternative to suggest even with save_as_docx?

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

my_doc <- read_docx()

lapply(list3, function(x) walk(x, write_word_table , my_doc))
print(my_doc, target = "C:/Users/PC/Desktop/D1.docx") %>% invisible() 

Thanks

1

There are 1 best solutions below

5
stefan On

While I would probably go for lapply to create the list of datasets when it comes to exporting I would go for a for loop but you can also use e.g. Reduce:

library(flextable)
library(officer)

write_word_table <- function(var, doc){
  doc %>%
    body_add_flextable(flextable(var)) %>% 
    body_add_break() 
}

my_doc <- read_docx()

for (x in list3) {
  for (var in x) {
    my_doc <- write_word_table(var, my_doc)
  }
}

print(my_doc, target = "D1.docx")

enter image description here

EDIT When I replace body_add_break by body_add_par I get all tables on one page. But perhaps I misunderstand what you are trying to achieve:

write_word_table <- function(var, doc){
  doc %>%
    body_add_flextable(flextable(var)) %>% 
    body_add_par("") 
}

my_doc <- read_docx()

for (x in list3) {
  for (var in x) {
    my_doc <- write_word_table(var, my_doc)
  }
}

print(my_doc, target = "D1.docx")

enter image description here

DATA

list3 <- lapply(seq(2), function(x) lapply(seq(3), function(x) head(mtcars, 3)))