rofficer

Edit Word table using officer package


Using "officer" I'm trying to edit the values of a Word table. Pretty straight forward to find the "paragraph" containing it

library(officer)

doc = read_docx('template.docx')
doc = cursor_begin(doc)
doc = cursor_reach(doc,"Some text")
print(doc)

and I get a document that looks like:

* Content at cursor location:
 row_id is_header cell_id                    text col_span row_span
1.1       1     FALSE       1                   D            1        1
1.5       2     FALSE       1                                1        1
1.9       3     FALSE       1             Some text          1        1
1.13      4     FALSE       1                                1        1
2.2       1     FALSE       2            More text           1        1

But, then what? There doesn't seem to be any way of directly altering the content of this table...


Solution

  • You can use body_replace_all_text for that task.

    library(officer)
    
    
    doc <- read_docx()
    doc <- body_add_table(doc, iris, style = "table_template")
    
    doc = cursor_reach(doc, "setosa")
    doc <- body_replace_all_text(doc, old_value = "setosa", 
      new_value = "coco", only_at_cursor = TRUE)
    print(doc, target = "test.docx")