Flextable output to .docx cannot be opened in Word

I've been trying to import a .csv file into R, then convert it to a flextable, then export the flextable into a Word .docx document. I use the following code

    library(tidyverse)
    library(readxl)
    library(scales)
    library(janitor)
    library(stringr)
    library(magrittr)
    library(officer)
    library(flextable)
    library(dplyr)
    
    # load data ---------------------------------------------------------------
    
    Rpops_survey <- read_csv("R-POPS Data Quant.csv")
    spec(Rpops_survey)
    
    # convert data ------------------------------------------------------------
    Rpops_survey_dframed <- as.data.frame(Rpops_survey)
    Rpops_ft1 <- flextable(Rpops_survey_dframed)
    Rpops_doctemp <- read_docx()
    Rpops_doctemp <- body_add_flextable(Rpops_doctemp, value = Rpops_ft1)
    
    # export data -------------------------------------------------------------
    fileout <- tempfile(fileext = ".docx")
    fileout <- "test.docx" 
    print(Rpops_doctemp, target = fileout)

The file is created, but trying to open it in Word produces the following error: Word docx error

1 answer

  • answered 2021-10-24 20:34 manro

    Maybe it is better to make it via R-Markdown.

    You should try this next: create a .Rmd file and paste in this code:

    ---
    title: "test"
    output:
      word_document: default
      pdf_document: default
    ---
    
    ```{r setup, include = FALSE}
    library(flextable)
    ft <- flextable(head(airquality))
    ```
    Here is the table: `r ft`
    

    And knit.

    Was an output .docx file created without any errors?

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum