英文:
How to search and replace text in PowerPoint, using OfficeR
问题
我正在使用 officer
来操作 PowerPoint 模板,以便用 r
中计算得到的值填充占位符。
是否有一种方法可以对幻灯片中的文本进行搜索和替换?
英文:
I am using officer
to manipulate a PowerPoint template in order to fill placeholders with values calculated in r
.
Is there a way to do a search-and-replace to the texts in a slide?
答案1
得分: 2
据我了解,“officer”仅为Word文件(docx
)提供了body_replace_all_text
函数,但没有为PowerPoint文件提供类似的函数。
幸运的是,slide$get()
函数提供了对相应幻灯片底层XML文档的访问权限。然后,库xml2
允许修改这些节点。希望这个代码片段能帮助其他人避免在包中进行令人沮丧的搜索。
library("officer")
library("xml2")
# 替换匹配xpath的所有标签中的文本的函数
xml_replace_text = function(xml, search, replace, xpath = "//a:t") {
# 替换单个文本节点的函数
replace_in_node = function(node, search, replace) {
xml_text(node) = gsub(pattern = search, replacement = replace, fixed = T, x = xml_text(node))
return()
}
text_nodes = xml_find_all(xml, xpath = xpath)
lapply(text_nodes, FUN=replace_in_node, search=search, replace=replace)
return()
}
# 在pptx文件中的幻灯片中搜索并替换文本的函数
replace_in_slide = function(ppt, slide_index=1, search, replace) {
xml_replace_text(ppt$slide$get_slide(slide_index)$get(), search, replace)
return()
}
# Übersichtsseite
ppt = read_pptx("template.pptx")
replace_in_slide(ppt, 2, "%placeholder%", "Test THREE")
print(ppt, target = "example.pptx")
请注意,只有在一个XML标签中实际存储了文本时才能进行替换。在将占位符放入文本后,请勿编辑占位符名称。
英文:
To my knowledge, officer
only provides the function body_replace_all_text
for Word files (docx
), but no such function for PowerPoint.
Fortunately, the slide$get()
function offers access to the XML document underlying the respective slide. The library xml2
then allows to modify these nodes. Hope this snippet will save others the frustrating search through the packages.
library("officer")
library("xml2")
# Function to replace text in all tags matching xpath
xml_replace_text = function(xml, search, replace, xpath = "//a:t") {
# Function to replace in a single text node
replace_in_node = function(node, search, replace) {
xml_text(node) = gsub(pattern = search, replacement = replace, fixed = T, x = xml_text(node))
return()
}
text_nodes = xml_find_all(xml, xpath = xpath)
lapply(text_nodes, FUN=replace_in_node, search=search, replace=replace)
return()
}
# Function to search and replace text in a slide in a pptx file
replace_in_slide = function(ppt, slide_index=1, search, replace) {
xml_replace_text(ppt$slide$get_slide(slide_index)$get(), search, replace)
return()
}
# Übersichtsseite
ppt = read_pptx("template.pptx")
replace_in_slide(ppt, 2, "%placeholder%", "Test THREE")
print(ppt, target = "example.pptx")
Note that replacing will only work if a text is actually stored in one XML tag. Avoid editing placeholder names after placing them in the text.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论