Make a table take up full page width with officer

I’m trying to make a table with the flextable package in R, and adjust the width to fit almost the entire width of the Word page. I’m using the functions table_width and fit_to_width, but it isn’t working as expected.

# Charger la bibliothèque pour manipuler les dataframes
library(officer)
library(flextable)

# Créer les données
colonne1 <- c("Nombre totaux d'arceaux vélo", "Nombre d'arceaux vélos installés")
colonne2 <- c(10, 5)

# Créer le dataframe
df <- data.frame(Colonne1 = colonne1, Colonne2 = colonne2)

#Mise en forme 
TABLEAU <- flextable(df) %>%
  align(align = "left", part = "all") %>%
  bg(bg = "#D3D3D3", part = "header") %>%
  bold(part = "header") %>%
  align(align = "left", part = "header") %>%
  set_caption(paste("BL", commune, "en", annee_prec)) %>%
  fit_to_width(max_width = 6.5)%>%
  autofit()

TABLEAU

# Créer un nouvel objet Word
doc <- read_docx()

# Ajouter le tableau au document Word
doc <- body_add_flextable(doc, value = TABLEAU)

# Sauvegarder le document Word (you need to change it for you)
print(doc, target = "Desktop/file.docx")

I’m trying to adjust the width of a table created with the flextable package in R to fit almost the entire width of the Word page. I’m using the functions table_width and fit_to_width, but the table isn’t adjusting as expected.

What i want

It seems that the issue lies in the fit_to_width function. Instead of using fit_to_width, you can try using the width function to set the desired width of the table. Here’s the modified code:

# Charger la bibliothèque pour manipuler les dataframes
library(officer)
library(flextable)

# Créer les données
colonne1 <- c("Nombre totaux d'arceaux vélo", "Nombre d'arceaux vélos installés")
colonne2 <- c(10, 5)

# Créer le dataframe
df <- data.frame(Colonne1 = colonne1, Colonne2 = colonne2)

#Mise en forme 
TABLEAU <- flextable(df) %>%
  align(align = "left", part = "all") %>%
  bg(bg = "#D3D3D3", part = "header") %>%
  bold(part = "header") %>%
  align(align = "left", part = "header") %>%
  set_caption(paste("BL", commune, "en", annee_prec)) %>%
  width(width = 6.5, part = "all") %>%  # Adjust the width as desired
  autofit()

TABLEAU

# Créer un nouvel objet Word
doc <- read_docx()

# Ajouter le tableau au document Word
doc <- body_add_flextable(doc, value = TABLEAU)

# Sauvegarder le document Word (you need to change it for you)
print(doc, target = "Desktop/file.docx")

In this modified code, the width function is used to set the width of the table to 6.5. You can adjust this value as needed to fit the table almost the entire width of the Word page.