rborderofficer

In officer package, how to add a simple border to body_add_table?


I'm using the officer package to create a Word document with some tables in it. I want the tables to have simple lines separating cells, but I don't know how to do it. I add each table with body_add_table(), and I know there is a function called fp_border(), but nowhere on the documentation or the internet I could find how to relate both functions. I tried calling fp_border() right before and right after read_docx(), and right before body_add_table(), but nothing works. I've also read that package “flextable” should be used instead, but in this case, what is the point in having a fp_border() function?

Looks like I will have to go with flextable, but I want to be sure.

PS: I got a very strange error here: The tag [table] is too similar to [table]. If you think this new tag should be allowed, discuss it on meta.


Solution

  • My solution goes along these lines:

    library(officer)
    library(flextable)
    
    tab = data.frame(...)
    set_flextable_defaults(split=F)
    dx = read_docx()
    dx = body_add_par(dx,'Some text',pos='after')
    dx = body_add_par(dx,'',pos='after')
    dx = body_add_par(dx,'Some more text',pos='after')
    dx = body_add_par(dx,'',pos='after')
    ft = flextable(tab)
    ft = set_header_labels(ft,values=gsub('.',' ',names(tab),fixed=T))
    ft = border_outer(ft,fp_border(width=0.5))
    ft = border_inner_h(ft,fp_border(width=0.5))
    ft = border_inner_v(ft,fp_border(width=0.5))
    ft = set_table_properties(ft,'autofit',width=1) # whole page width, 1 = 100%
    ft = fontsize(ft,size=10, part='all')
    dx = body_add_flextable(dx,ft)
    dx = body_add_break(dx,pos='after')