R-ReporteRs软件包-具有动态值的Word模板 [英] R - ReporteRs package - word template with dynamic values

查看:168
本文介绍了R-ReporteRs软件包-具有动态值的Word模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好人,

我正在从事基于单词的报告自动化任务.这些报告基本上是一些标准文本,十几个图表,一些基于逻辑需要填充的数字/趋势文本值.趋势文本,数值或图表将从后端数据库生成.

I'm working on a word based reports automation task. These reports are basically some standard text, a dozen or so charts, some numeric/trend text values that I need to populated based on logic. The trend text, numeric values or charts are to be generated from backend database.

我能够使用数据库生成带有图表的空白文档,我使用的R包包括ReporteRs,RODBC,官员和相应的依赖包,用于图表的ggplot2. 但是,我想实现的是,有一个带有某种占位符的Word文档模板,可以在其中放置图表和这些数字值.

I'm able to produce a blank document with charts using database, the R packages I used are ReporteRs, RODBC, officer and corresponding dependency packages, ggplot2 for charts. However what I would like to achieve is, have a word document template with some sort of placeholders where I can put the charts and these numeric values.

我的基本代码如下

    doc <- docx(title="my doc")
    mychart <- ggplot(.....)
    doc <- addPlot(doc, fun=print, x = mychart)
    writeDoc(doc, filename)

任何人都可以建议如何完成此任务.我在docx中看到了模板参数的用法,但是找不到在Word文档中将值放入占位符或将图表置于特定占位符的合适示例.

Can anyone advise how to approach this task. I saw usage of template parameter in docx but I couldn't find suitable examples of putting values in placeholders or putting charts at particular placeholders inside Word document.

希望我已经清楚地解释了,如果没有,请告诉我.

Hope I've explained it clearly, if not please let me know.

推荐答案

我建议为此使用VBA,而不是R.对Word中的DocVariables进行一些google研究.将一些DocVariables添加到Word模板,将分析保留在Excel中,然后将Excel中的内容推入Word DocVariables.使用下面的脚本(可在Excel中运行)使所有功能正常运行.

I would recommend using VBA for this, not R. Do some google-research on DocVariables in Word. Add some DocVariables to your Word template, keep your analytics in Excel, and then push what you have in Excel into the Word DocVariables. Use the script below, which runs in Excel, to make everything work.

Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next

objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value


objWord.ActiveDocument.Fields.Update

'On Error Resume Next
objWord.Visible = True

End Sub

最后,从Excel添加对Word的引用. Tools > References > Microsoft Word xxx Object Library.

Finally, add a reference to Word, from Excel. Tools > References > Microsoft Word xxx Object Library.

这篇关于R-ReporteRs软件包-具有动态值的Word模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆