使用officer包编辑Word表格

5

我正在尝试使用“officer”编辑Word表格的值。找到包含它的“段落”非常简单。

library(officer)

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

然后我得到了一个看起来像这样的文档:

* 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

但是,那么呢?似乎没有直接改变这个表格内容的方式...

1个回答

3
您可以使用 body_replace_all_text 来完成这个任务。
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")

太好了!虽然我希望能够向空单元格添加文本,但我可以在那里添加占位符文本并替换它。这很有效,谢谢! - Paul Igor Costea
根据您真正想要做什么,可能会有更简单的解决方案。例如,您可以从这些数据中获取一个data.frame(请参见此处:https://davidgohel.github.io/officer/articles/officer_reader.html#word-tables),然后将单词表替换为修改后的数据版本。 - David Gohel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接