R - ReporteRs package - word template with dynamic values

十年热恋 提交于 2019-12-06 10:00:22

Ok I've figured out how to achieve it finally.

MS-Word allows putting placeholders in document and bookmark them so that values/data/images can be put in their place.

You can create a normal word document(not as word template) and add your static content in it along with bookmarked placeholders as per your requirements. Please refer here to know how to add bookmarks , Word doesn't show existing bookmarks by default, to enable that go to File -> Options -> Advanced check Show bookmarks, you'll see [your_bookmark] thing in square brackets.

Next in R, try following code

doc <- docx(title="title", template="c://above_template.docx")
doc = addPlot(doc, x=myChartVariable, bookmark="your_chart_bookmark)
writeDoc(doc, "c://new_doc_file_path.docx:)

you should see new file with a chart substituted where you put its placeholder.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!