Word documents update from R with doconv

[This article was first published on R on ArData, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

If you are a Word user, it is now possible to automatically update fields and tables of contents instead of having to do it manually from Word, provided you have Word available on the PC hosting R.

According to an issue on github (link) and other requests from users on the subject, the “doconv” package has evolved to answer this.

Let’s take the example of a ‘.docx’ file generated by the following code with package ‘officedown’:

 title: "Exemple with references"
 output: 
     officedown::rdocx_document:
       toc: true
 ---
 
 ```{r setup, include=FALSE}
 knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
 library(officer)
 library(officedown)
 library(ggplot2)
 library(flextable)
 ```
 
 This is `r run_word_field("DOCPROPERTY \"custom_field_value\" \\* MERGEFORMAT")`.
 
 ## Figure 
 
 ```{r}
 ggplot(iris, mapping = aes(x = Sepal.Length, y = Petal.Length)) +
   geom_point()
 ```
 
 ## Table
 
 ```{r}
 flextable(head(iris)) |> autofit()
 ```

The document exemple.docx will contain a table of contents and an unset field named custom_field_value.

It is generated by pandoc and the tables of contents, references and in general all the fields calculated by Word are not updated unless the user intervenes manually. The user has to open Word and refresh these fields himself to get for example a table of contents with the right values of titles and corresponding page numbers.

Result with no manual intervention

doconv::docx_update()` will automate this manual process and update the Word document.

library(officer)
library(doconv)
x <- read_docx("example.docx")
x <- set_doc_properties(
  x,
  custom_field_value = "trop cool"
)
print(x,target = "updated-example.docx")
docx_update(input = "updated-example.docx")

The previous code set the value “trop cool” to the field named custom_field_value with the function set_doc_properties(). Then the function docx_update() is used to update TOCs and Word computed fields.

The resulting file updated-example.docx looks like this:

Result doconv-update

To leave a comment for the author, please follow the link and comment on their blog: R on ArData.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)