0

我有一个使用wdGet(filename="exOut.doc",visible=FALSE). 该文件中已经包含我使用 html 和cat(img, file=outputDoc, sep="\n", append=TRUE).

我需要在文档末尾插入一个表格,但wdTable(format(head(testTable)))将表格放在 word 文档的最顶部。我怎样才能解决这个问题?

另外,第二个问题:我有很多表需要插入到我的文档中,因此需要使用循环。下面是演示我的问题的示例代码。这对我来说真的很奇怪:当我单步执行代码并逐行运行时,它不会产生错误并且我有一个输出文档。如果我一次运行所有内容,我会收到“无法打开连接错误”。我不明白这怎么可能。与一次运行所有完全相同的代码相比,一次运行每一行产生不同的结果怎么可能?

rm(list=ls())

library(R2wd)
library(png)

outputForNow<-"C:\\Users\\dirkh_000\\Downloads\\"
outputDoc<-paste(outputForNow,"exOut.doc",sep="")
setwd(outputForNow)

# Some example plots
for(i in 1:3) 
{ 
  dir.create(file.path(paste("folder",i,sep="")))
  setwd(paste("folder",i,sep="")) # Note that images are all in different folders
  png(paste0("ex", i, ".png"))
  plot(1:5)
  title(paste("plot", i))
  dev.off()
  setwd(outputForNow)
}

setwd(outputForNow)
# Start empty word doc
cat("<body>", file="exOut.doc", sep="\n")

# Retrieve a list of all folders
folders<-dir()[file.info(dir())$isdir]
folders<-folders[!is.na(folders)]

# Cycle through all folders in working directory
for(folder in folders){
  setwd(paste(outputForNow,folder,sep=""))
  # select all png files in working directory
  for(i in list.files(pattern="*.png"))
  {
    temp<-paste0('<img src=','\"',gsub("[\\]","/",folder),"/", i, '\">')
    cat(temp, file=outputDoc, sep="\n", append=TRUE)
    setwd(paste(outputForNow,folder,sep=""))
  }
  setwd(outputForNow)
  cat("</body>", file="exOut.doc", sep="\n", append=TRUE)
  testTable<-as.data.frame(cbind(1,2,3))
  wdGet(filename="exOut.doc",visible=FALSE)
  wdTable(format(head(testTable))) ## This produces a table at the top and not the bottom of the document
  wdSave(outputDoc)
  wdQuit() # NOTE that this means that the document is closed and opened over and over again in the loop otherwise cat() will throw an error
}

上面的代码产生:

Error in file(file, ifelse(append, "a", "w")) : 
  cannot open the connection

谁能告诉我为什么会发生这种情况以及如何解决?谢谢,麻烦您了。如果您知道我以错误的方式解决此问题,请推荐一种完全不同的方法,但也请解释我做错了什么。

4

1 回答 1

0

要启动 DescTools 包和 Word 文档,请使用以下内容(显然,已针对您的路径结构进行了修改):

library(DescTools)
library(RDCOMClient)
report <- GetNewWrd(template = "C:/Users/Rees/Documents/R/win-library/3.0/R2DOCX/templates/TEMPLATE_03.docx")

根据评论添加

在 Word 中为您的报告创建模板。也许你称之为 TEMPLATE.docx。将其保存在您的文档目录(或您保存 Word 文档的任何目录中。然后

report <- GetNewWrd(template = " "C:/Users/dirkh_000/Documents/TEMPLATE.docx")

此后,每次创建绘图时,添加以下行:

WrdPlot(wrd = report)

该图被插入到指定目录的 TEMPLATE.docx Word 文档中。

WrdTable(wrd = report) 也一样

于 2014-12-01T00:36:22.767 回答