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

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

问题描述

大家好,

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

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 进行一些谷歌研究.将一些 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 的引用.<代码>工具>参考文献Microsoft Word xxx 对象库.

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

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

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