Is it possible to copy content from one Word document to another using R officer package?

44 Views Asked by At

I need to copy a table from one document to another. In officer package there is a function cursor_reach that allows to set a virtual cursor in a specified position in the document. What I want to do is to locate a table by its header text (the header is always before table) and then move somehow to the table itself and copy it to another document or at least save the captured table as a new document. Is it possible with officer package?

I know that using xml2 package copying xml nodes is possible and maybe it can be a workaround. Although, many of my tries ended with a corrupted structure. I guess Word format is more restricted on moving xml nodesets. For example copying <w:p> element is OK, but when I try to copy some nested nodes inside it the resulting document is corrupted.

library(officer)
library(xml2)
# this works fine
src_doc <- read_docx("src.docx")
src_xml <- src_doc$doc_obj$get()
tbl <- xml_find_first(
  src_xml,
  ".//w:p"
)
new_doc <- officer::body_add_xml(x = src_doc, as.character(tbl))
print(new_doc, "new.docx")
# this works too
tbl <- xml_find_first(
  src_xml,
  ".//w:tbl"
)
new_doc <- officer::body_add_xml(x = src_doc, as.character(tbl))
print(new_doc, "new.docx")
# this doesn't work - document is corrupted, even though documents' xml structure seems to be OK
tbl <- xml_find_first(
  src_xml,
  ".//w:t"
)
new_doc <- officer::body_add_xml(x = src_doc, as.character(tbl))
print(new_doc, "new.docx")

Is there a function in officer package to copy content safely?

0

There are 0 best solutions below