• Home
  • Template
  • Styles
  • Formating tables
  • Insert into a Word bookmark

Template

You may need to generate docx documents in a particular corporate template (with specific fonts, colour schemes, logos, etc.).

Prepare a docx file that will be used as template (or use an existing one).

require( R2DOCX )
# Word document to use as base document or a template
template.file = "D:/templates/My_Template.docx"
# Create a new object
doc = new("Docx", title = "example", basefile = template.file )

That's it. This file is then duplicated in memory. R outputs sent to the object 'doc' will go into that copy.

By default, an empty document is used (located into the package directory).

Styles

Available styles are the paragraph styles contained in the template.

require( R2DOCX )
# Create a new object with the default template
doc = new("Docx", title = "example" )
styles( doc )
# [1] "Normal"                  "Titre1"                  "Titre2"                 
# [4] "Titre3"                  "Titre4"                  "Titre5"                 
# [7] "Titre6"                  "Titre7"                  "Titre8"                 
# [10] "Titre9"                  "Titre"                   "Sous-titre"             
# [13] "Citation"                "Citationintense"         "Lgende"                 
# [16] "En-ttedetabledesmatires" "Sansinterligne"          "Paragraphedeliste"      
# [19] "PlotReference"           "En-tte"                  "Pieddepage"             
# [22] "Titre10"                 "BulletList"              "Titre20"                
# [25] "TitleDoc"

Paragraphs

Function addParagraph require parameter stylename whose value must be one of the names returned by the function styles.

doc = addParagraph( doc, value = "Normal text", stylename = "Normal" )

Headers

Function addHeader need to know which styles are corresponding to which title level (1 ; 1.1 ; 1.1.1 ; etc.).

When template is read, R2DOCX try to guess what are theses styles. If he do not succeed, you will see that error when addHeader will be called:

Error in addHeader(...
You must defined header styles via setHeaderStyle first.

You have to use function setHeaderStyle to indicate which available styles are meant to be used as header styles.

doc = new("Docx", title = "My example" )
styles( doc )
# [1] "Normal"                  "Titre1"                  "Titre2"                 
# [4] "Titre3"                  "Titre4"                  "Titre5"                 
# [7] "Titre6"                  "Titre7"                  "Titre8"                 
#[10] "Titre9"                  "Policepardfaut"          "TableauNormal"          
# ...
doc = setHeaderStyle(doc
        , stylenames = c("Titre1", "Titre2", "Titre3"
                , "Titre4", "Titre5", "Titre6"
                , "Titre7", "Titre8", "Titre9" ) )
doc = addHeader( doc, "title 1", 1 )

Tables of contents

Functions addTOC has an optional argument stylename, if used, a table of contents will be created with entries formated with style specified. An example of usage is a table of contents of the produced graphics:

doc = addPlot( doc, function() plot( rnorm(10), rnorm(10) )
        , width = 10, height = 8, legend="graph example 1"
        , stylename="PlotReference" )
doc = addPlot( doc, function() plot( rnorm(100), rnorm(100) )
        , width = 10, height = 8, legend="graph example 2"
        , stylename="PlotReference" )
doc = addTOC( doc, stylename="PlotReference" )


Do not use styles names that contains special character. In France for example, the default style named "Legend" becomes "Légende" and is returned as "Lgende" by the styles R function. The workaround is to create a new style based on "Légende" and to name it "Legende". It will be then a valid name to use with R2DOCX.

Formating tables

You can define table formating properties. It is first necessary to understand the model implemented :

grouped header row 1   grouped header row p
column header 1 column header 2 column header ... column header ... column header p
data[1,1] data[1,2] data[1,...] data[1,...] data[1,p]
data[...,1] data[...,2] data[...,...] data[...,...] data[...,p]
data[n,1] data[n,2] data[n,...] data[n,...] data[n,p]

In few words:

  • Headers are columns labels displayed
  • Grouped headers is a row preceding headers where columns labels can be gathered under a label. This row is optional.
  • Each column has one of the following reporting types : double, integer, character, percent, date, datetime.
  • Data will be formated conditionnaly to the reporting types of each columns, for example, all numeric columns will be formated the same

Elements that can be formated are cells, paragraphs of text, texts

Options are available to define:

  • the number of digits to the left of the decimal point for numeric data and percent data.
  • the minimum number of digits to the right of the decimal point of double data or the minimum number of digits to display for integer data.
  • percent symbol to add after data of reporting type 'percent'

Simple example

This code

# let's format header labels with a bold font and a centered paragraph
# also, change the number of digits to the left of the decimal point for double data
myformat = tableProperties(
        header.text = textProperties(font.weight="bold")
        , header.par = parProperties( text.align = "center" )
        , fraction.double.digit = 4
)
doc = addTable( doc, iris[1:5,], formats = myformat )

should produces the following result

Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species
5.1000
3.5000
1.4000
0.2000
setosa
4.9000
3.0000
1.4000
0.2000
setosa
4.7000
3.2000
1.3000
0.2000
setosa
4.6000
3.1000
1.5000
0.2000
setosa
5.0000
3.6000
1.4000
0.2000
setosa

textProperties

Use function textProperties to specify formating text properties.

Argument name Details Expected Value
color font color a string value (e.g. "#000000" or "black")
font-size font size in px an integer value : 0>= value
font-weight font weight normal or "bold"
font-style font style normal or "italic"
font-family font family name (Arial, Times, etc.) a string value : must be an available font name, e.g. Arial, Times, etc.
textProperties(font.size = 10, font.weight = "bold" )
textProperties(font.size = 10, font.weight = "bold", color = "red" )

parProperties

Use function parProperties to specify formating paragraph properties.

Argument name Details Expected Value
text-align text alignment a string value : "left" or "right" or "center" or "justify"
padding-bottom space after paragraph in px an integer value : 0>= value
padding-top space before paragraph in px an integer value : 0>= value
padding-left space on the left of paragraph in px an integer value : 0>= value
padding-right space on the right of paragraph in px an integer value : 0>= value

An additional argument is available as shortcut:

Argument name Details Expected Value
padding cell bottom, top, left and right padding integer value : 0>= value. It sets all paddings to the same value.
parProperties(text.align = "center", padding = 3 )
parProperties(text.align = "right", padding.left = 4, padding.right = 4)

cellProperties

Use function cellProperties to specify formating cell properties.

Argument name Details Expected Value
border.bottom.colorborder bottom colora string value (e.g. "#000000" or "black")
border.bottom.styleborder bottom stylea string value : "single" or "none" or "hidden" or "double" or "dotted" or "dashed" or "inset" or "outset"
border.bottom.widthborder bottom widthan integer value : 0>= value
border.left.colorborder left colora string value (e.g. "#000000" or "black")
border.left.styleborder left stylea string value : "single" or "none" or "hidden" or "double" or "dotted" or "dashed" or "inset" or "outset"
border.left.widthborder left widthan integer value : 0>= value
border.top.colorborder top colora string value (e.g. "#000000" or "black")
border.top.styleborder top stylea string value : "single" or "none" or "hidden" or "double" or "dotted" or "dashed" or "inset" or "outset"
border.top.widthborder top widthan integer value : 0>= value
border.right.colorborder right colora string value (e.g. "#000000" or "black")
border.right.styleborder right stylea string value : "single" or "none" or "hidden" or "double" or "dotted" or "dashed" or "inset" or "outset"
border.right.widthborder right widthinteger value : 0>= value
vertical.aligncell content vertical alignmenta string value : "center" or "top" or "bottom"
padding.bottomcell bottom paddinginteger value : 0>= value
padding.topcell top paddinginteger value : 0>= value
padding.leftcell left paddinginteger value : 0>= value
padding.rightcell right paddinginteger value : 0>= value
background.colorcell background colora string value (e.g. "#000000" or "black")

Additional arguments are available as shortcuts:

Argument name Details Expected Value
paddingcell bottom, top, left and right paddinginteger value : 0>= value. It sets all paddings to the same value.
border.widthcell bottom, top, left and right border widthinteger value : 0>= value. It sets all border widths to the same value.
border.stylecell bottom, top, left and right border stylea string value : "single" or "none" or "hidden" or "double" or "dotted" or "dashed" or "inset" or "outset". It sets all border styles to the same value.
cellProperties( border.color = "gray" )
cellProperties(border.left.width = 0, border.right.width = 0
         , border.bottom.width = 2, border.top.width = 0
         , padding.bottom = 2, padding.top = 2
         , padding.left = 2, padding.right = 2 )

tableProperties

Use function tableProperties to specify formating table properties.

Argument name Details Expected Value
header.textheader text formatting propertiestextProperties
header.parheader paragraph formatting propertiesparProperties
header.cellheader cell formatting propertiescellProperties
groupedheader.textgrouped header text formatting propertiestextProperties
groupedheader.pargrouped header paragraph formatting propertiesparProperties
groupedheader.cellgrouped header cell formatting propertiescellProperties
double.text"double" columns formatting text propertiestextProperties
double.par"double" columns formatting paragraph propertiesparProperties
double.cell"double" columns formatting cell propertiescellProperties
integer.text"integer" columns formatting text propertiestextProperties
integer.par"integer" columns formatting paragraph propertiesparProperties
integer.cell"integer" columns formatting cell propertiescellProperties
percent.text"percent" columns formatting text propertiestextProperties
percent.par"percent" columns formatting paragraph propertiesparProperties
percent.cell"percent" columns formatting cell propertiescellProperties
character.text"character" columns formatting text propertiestextProperties
character.par"character" columns formatting paragraph propertiesparProperties
character.cell"character" columns formatting cell propertiescellProperties
date.text"date" columns formatting text propertiestextProperties
date.par"date" columns formatting paragraph propertiesparProperties
date.cell"date" columns formatting cell propertiescellProperties
datetime.text"datetime" columns formatting text propertiestextProperties
datetime.par"datetime" columns formatting paragraph propertiesparProperties
datetime.cell"datetime" columns formatting cell propertiescellProperties
percent.addsymbola string value to add after percent data (default to %)character
integer.digitminimum number of digits to display (to the left of the decimal point for data of type percent and double)an integer value : 0>= value
fraction.double.digitminimum number of digits to display to the right of the decimal point (for data of type double)an integer value : 0>= value
fraction.percent.digitminimum number of digits to display to the right of the decimal point (for data of type percent)an integer value : 0>= value

Additional arguments are available as shortcuts:

Argument name Details Expected Value
data.cellcell formatting properties for all data columnsA cellProperties object. It sets all cells to the same value (double.cell, character.cell, integer.cell, etc.).
data.parparagraph formatting properties for all data columnsA parProperties object. It sets all paragraphs to the same value (double.par, character.par, integer.par, etc.).
data.texttext formatting properties for all data columnsA textProperties object. It sets all texts to the same value (double.text, character.text, integer.text, etc.).
header.cellProperties = cellProperties( border.left.width = 0, border.right.width = 0
        , border.bottom.width = 1, border.top.width = 0, padding = 3 )
data.cellProperties = cellProperties( border.left.width = 0, border.right.width = 0
        , border.bottom.width = 1, border.top.width = 0, padding = 2 )

header.textProperties = textProperties( font.size = 10, font.weight = "bold" )
data.textProperties = textProperties( font.size = 10 )

leftPar = parProperties( text.align = "left", padding.left = 4, padding.right = 4)
rightPar = parProperties( text.align = "right", padding.left = 4, padding.right = 4)
centerPar = parProperties( text.align = "center", padding.left = 4, padding.right = 4)

my.formats = tableProperties(
        character.par = leftPar
        , percent.par = rightPar
        , double.par = rightPar
        , integer.par = rightPar
        , groupedheader.par = centerPar
        , groupedheader.text = header.textProperties
        , groupedheader.cell = header.cellProperties
        , header.cell = header.cellProperties
        , header.par = centerPar
        , header.text = header.textProperties
        , data.cell = data.cellProperties
        , data.text = data.textProperties
)

Replace Word bookmarks by tables, paragraphs and plots

MS Work bookmarks can be used to define a named location in your document.

Functions addTable, addPlot, addParagraph and addImage can send respective outputs into theses bookmarks.

Theses functions have an optional argument bookmark, if used, content (table, plots, paragraphs or images) will replace the whole paragraph containing the bookmark.


A paragraph in the template document can only contain one bookmark. Function addParagraph should be used if you want to replace multiple values in paragraphs.

Complete example

We are expecting the following output file document.docx

require( R2DOCX )

# Word document to write
docx.file = "document.docx"

# Remove file if it already exists
if(file.exists( docx.file ))
        file.remove( docx.file )

# Word document to use as base document or a template
template.file = file.path( find.package("R2DOCX"), "templates/bookmark_example.docx", fsep = "/" )

# create document
doc = new("Docx", title = "My example", basefile = template.file )


# replace bookmarks 'AUTHOR' and 'REVIEWER' located in 'ttest_example.docx' by dummy values
doc = addParagraph( doc
                , value = c( "James Sonny Crockett", "Ricardo Rico Tubbs" )
                , stylename = "Normal"
                , bookmark = "AUTHOR" )
doc = addParagraph( doc
                , value = c( "Martin Marty Castillo" )
                , stylename = "Normal"
                , bookmark = "REVIEWER" )



# replace bookmarks 'DATA' and 'CONFINT' located in 'ttest_example.docx' by data.frame objects 'data' and 'conf.int'
doc = addTable( doc
                , iris[5:10,]
                , bookmark = "DATA" )


## replace bookmark 'PLOT' by a plot
doc = addPlot( doc
                , fun = plot
                , x = rnorm( 100 )
                , y = rnorm (100 )
                , main = "base plot main title"
                , bookmark = "PLOT")


doc = addParagraph( doc, value = c( "Header 1" ), stylename = "NAMESTYLE", bookmark = "COLNAME1" )
doc = addParagraph( doc, value = c( "Header 2" ), stylename = "NAMESTYLE", bookmark = "COLNAME2" )
doc = addParagraph( doc, value = c( "Header 3" ), stylename = "NAMESTYLE", bookmark = "COLNAME3" )
doc = addParagraph( doc, value = c( "Row name 1" ), stylename = "NAMESTYLE", bookmark = "ROWNAME1" )
doc = addParagraph( doc, value = c( "Row name 2" ), stylename = "NAMESTYLE", bookmark = "ROWNAME2" )
doc = addParagraph( doc, value = c( "Hello World!" ), stylename = "DATASTYLE", bookmark = "ANYDATA" )



writeDoc( doc, docx.file )


if( interactive() ) {
        out = readline( "Open the docx file (y/n)? " )
        if( out == "y" ) browseURL( file.path(getwd(), docx.file ) )
}