R Officer 更新形状的文本

R Officer Update the text of a shape

我正在使用 officer 为我的管理生成每周一次的 PowerPoint 演示文稿。 他们向我提供了他们希望使用的模板。 除了给我带来一些困难的一部分外,我已经自动化了整个过程,我希望有人能提供帮助

他们模板中的第一张幻灯片是一张非常漂亮的封面幻灯片,但包含一个文本框,其中包含报告要处理的周数,例如 Report Week 5。我希望每周更改此报告 运行。下一次迭代将是 Report Week 6。当我在 windows

中按 ALT+F10 时,文本框的名称称为 TextField 26

我尝试了here, here and here

中的许多解决方案

我似乎无法在模板中引用幻灯片本身。我在 GITHUB 上看到了与类似问题相关的回复,其中的建议是删除旧形状并 re-add 它。我很乐意这样做,但我还是无法引用标题幻灯片。

我非常感谢任何人对此的见解

非常感谢您的宝贵时间

为了结束我的评论,我写了一个应该可以工作的函数。不幸的是,RDCOMClient 软件包确实需要您在 windows 计算机上才能工作

devtools::install_github("omegahat/RDCOMClient")
library(RDCOMClient)

ReplaceTextInObject <- function(path, Find, Replace, SlideNum = NULL){
  ppApp <- COMCreate("powerpoint.application")
  #Requires absolute paths from C drive
  path <- normalizePath(c("C://Users",path), winslash = "\")[2] 
  ppoint <- ppApp[["Presentations"]]$Open(path, WithWindow = F)
  slides <- 1:ppoint$Slides()$Count()
  #if SlideNum is NULL - loop through each slide
  if(!is.null(SlideNum)&&
     all(SlideNum%%1)==0&&
     all(SlideNum<=ppoint$Slides()$Count())){
    slides <- SlideNum
  } else{
    stop("m must be either an integer or NULL")
  } 

  for(j in slides){
    Slide <- ppoint$Slides(j)
    n <- Slide$Shapes()$Range()$Count() # Total number of shape objects on slide
    #if there are shapes with text - attempt find and replace
    if(n>0){
      for(i in 1:n){
        if(Slide$Shapes(i)$HasTextFrame()==-1&&
           Slide$Shapes(i)$TextFrame()$HasText()==-1){
             Slide$Shapes(i)$TextFrame()$TextRange()$Replace(FindWhat = Find,
                                                             ReplaceWhat = Replace)
        }
      }
    }
  }

  ppoint$Save()
  ppoint$Close()
  rm(Slide, ppoint, ppApp)
}

此函数将获取幻灯片编号,然后浏览幻灯片中的所有对象。如果对象(或形状 VBA 在文档中列出了它们)可以包含文本并且有文本,那么我们将尝试在该形状对象中使用查找和替换功能。

如果您知道确切的形状索引,则无需费心使用循环,但这会为您完成大部分繁重的工作。因此,如果文本字段在您的模板中确实是唯一的,这应该可以解决您的问题。

我认为您将此占位符放在模板中而不是现有幻灯片中会使事情更易于管理。但是,如果您使用的 powerpoint 其中第一张幻灯片包含一个名为 "TextField 26" 的空形状,则官员代码将为:

library(officer)
doc <- read_pptx("update_shape_text.pptx")
doc <- ph_add_text(doc, str = "Report Week 5", ph_label = "TextField 26") 
print(doc, "result.pptx")

请注意,我无法附加 update_shape_text.pptx,所以我使用了 github 问题,以便您可以获取文件。 https://github.com/davidgohel/flextable/issues/189